下面列出了java.util.Comparator#reverseOrder ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(dataProvider = "snapshot")
public void snapshot(boolean ascending, int limit, long clock, Function<Long, Long> transformer) {
int count = 21;
timerWheel.nanos = clock;
int expected = Math.min(limit, count);
Comparator<Long> order = ascending ? Comparator.naturalOrder() : Comparator.reverseOrder();
List<Long> times = IntStream.range(0, count).mapToLong(i -> {
long time = clock + TimeUnit.SECONDS.toNanos(2 << i);
timerWheel.schedule(new Timer(time));
return time;
}).boxed().sorted(order).collect(toList()).subList(0, expected);
when(transformer.apply(anyLong())).thenAnswer(invocation -> invocation.getArgument(0));
assertThat(snapshot(ascending, limit, transformer), is(times));
verify(transformer, times(expected)).apply(anyLong());
}
/**
* Return the string comparator to use for the given order name.
*
* @param orderKey the name of the order to apply. If null, default to {@link Order#ASC}.
* @return the string comparator to use for the given order name.
*/
private static Comparator<Comparable> getOrderComparator(Order orderKey) {
final Comparator<Comparable> comparisonOrder;
if (orderKey == null) {
comparisonOrder = Comparator.naturalOrder();
} else {
switch (orderKey) {
case ASC:
comparisonOrder = Comparator.naturalOrder();
break;
case DESC:
comparisonOrder = Comparator.reverseOrder();
break;
default:
// this should not be possible
throw new TDPException(ILLEGAL_ORDER_FOR_LIST, build().put("order", orderKey));
}
}
return comparisonOrder;
}
/**
* Prune a collection of facet trees, in order to remove nodes which are
* unlikely to be relevant. "Relevant" is defined here to be either
* entries with direct hits, or entries with a pre-defined number of
* child nodes with direct hits. This can remove several top-level
* layers from the tree which don't have direct hits.
* @param unprunedTrees the trees which need pruning.
* @return a sorted list of pruned trees.
*/
private Collection<TreeFacetField> stripNonRelevantTrees(Collection<TreeFacetField> unprunedTrees) {
// Use a sorted set so the trees come out in count-descending order
Set<TreeFacetField> pruned = new TreeSet<>(Comparator.reverseOrder());
for (TreeFacetField tff : unprunedTrees) {
if (tff.getCount() > 0) {
// Relevant - entry has direct hits
pruned.add(tff);
} else if (checkChildCounts(tff)) {
// Relevant - entry has a number of children with direct hits
pruned.add(tff);
} else if (tff.hasChildren()) {
// Not relevant at this level - recurse through children
pruned.addAll(stripNonRelevantTrees(tff.getHierarchy()));
}
}
return pruned;
}
public void testReverseComparator() {
Comparator<String> cmpr = Comparator.reverseOrder();
Comparator<String> cmp = cmpr.reversed();
assertEquals(cmp.reversed(), cmpr);
assertEquals(0, cmp.compare("a", "a"));
assertEquals(0, cmpr.compare("a", "a"));
assertTrue(cmp.compare("a", "b") < 0);
assertTrue(cmpr.compare("a", "b") > 0);
assertTrue(cmp.compare("b", "a") > 0);
assertTrue(cmpr.compare("b", "a") < 0);
}
@Test
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Override
public Comparator<? super BigDecimal> getComparator() {
if (step.signum() < 0) {
return Comparator.reverseOrder();
}
return null;
}
public void testReverseComparator() {
Comparator<String> cmpr = Comparator.reverseOrder();
Comparator<String> cmp = cmpr.reversed();
assertEquals(cmp.reversed(), cmpr);
assertEquals(0, cmp.compare("a", "a"));
assertEquals(0, cmpr.compare("a", "a"));
assertTrue(cmp.compare("a", "b") < 0);
assertTrue(cmpr.compare("a", "b") > 0);
assertTrue(cmp.compare("b", "a") > 0);
assertTrue(cmpr.compare("b", "a") < 0);
}
public List<Product> getProductsSortedByHits(List<Order> orders) {
List<OrderLine> lines1 = new ArrayList<>();
orders.stream()
.filter(order -> order.getStatus() == Order.Status.ACTIVE || order.getDeliveryDueDate()
.isAfter(LocalDate.now().minusWeeks(1)))
.map(Order::getOrderLines).forEach(lines1::addAll);
Map<Product, Integer> productHits = new HashMap<>();
for (OrderLine line : lines1) {
int newCount = line.getCount() + productHits.getOrDefault(line.getProduct(), 0);
productHits.put(line.getProduct(), newCount);
}
System.out.println("productHits: " + productHits);
Map<Integer, List<Product>> hitsToProducts = new TreeMap<>(Comparator.reverseOrder());
for (Product key : productHits.keySet()) {
Integer value = productHits.get(key);
List<Product> oldList = hitsToProducts.getOrDefault(value, new ArrayList<>());
oldList.add(key);
hitsToProducts.put(value, oldList);
}
System.out.println("hitsToProducts: " + hitsToProducts);
List<Product> topProducts = new ArrayList<>();
for (Integer hits : hitsToProducts.keySet()) {
List<Product> list = hitsToProducts.get(hits);
list.sort(comparing(Product::getName));
topProducts.addAll(list);
}
return topProducts;
}
public List<Product> getProductsSortedByHits(List<Order> orders) {
List<OrderLine> lines1 = new ArrayList<>();
orders.stream()
.filter(order -> order.getStatus() == Order.Status.ACTIVE || order.getDeliveryDueDate()
.isAfter(LocalDate.now().minusWeeks(1)))
.map(Order::getOrderLines).forEach(lines1::addAll);
Map<Product, Integer> productHits = new HashMap<>();
for (OrderLine line : lines1) {
int newCount = line.getCount() + productHits.getOrDefault(line.getProduct(), 0);
productHits.put(line.getProduct(), newCount);
}
System.out.println("productHits: " + productHits);
Map<Integer, List<Product>> hitsToProducts = new TreeMap<>(Comparator.reverseOrder());
for (Product key : productHits.keySet()) {
Integer value = productHits.get(key);
List<Product> oldList = hitsToProducts.getOrDefault(value, new ArrayList<>());
oldList.add(key);
hitsToProducts.put(value, oldList);
}
System.out.println("hitsToProducts: " + hitsToProducts);
List<Product> topProducts = new ArrayList<>();
for (Integer hits : hitsToProducts.keySet()) {
List<Product> list = hitsToProducts.get(hits);
list.sort(comparing(Product::getName));
topProducts.addAll(list);
}
return topProducts;
}
public List<Product> getProductsSortedByHits(List<Order> orders) {
List<OrderLine> lines1 = new ArrayList<>();
orders.stream()
.filter(order -> order.getStatus() == Order.Status.ACTIVE || order.getDeliveryDueDate()
.isAfter(LocalDate.now().minusWeeks(1)))
.map(Order::getOrderLines).forEach(lines1::addAll);
Map<Product, Integer> productHits = new HashMap<>();
for (OrderLine line : lines1) {
int newCount = line.getCount() + productHits.getOrDefault(line.getProduct(), 0);
productHits.put(line.getProduct(), newCount);
}
System.out.println("productHits: " + productHits);
Map<Integer, List<Product>> hitsToProducts = new TreeMap<>(Comparator.reverseOrder());
for (Product key : productHits.keySet()) {
Integer value = productHits.get(key);
List<Product> oldList = hitsToProducts.getOrDefault(value, new ArrayList<>());
oldList.add(key);
hitsToProducts.put(value, oldList);
}
System.out.println("hitsToProducts: " + hitsToProducts);
List<Product> topProducts = new ArrayList<>();
for (Integer hits : hitsToProducts.keySet()) {
List<Product> list = hitsToProducts.get(hits);
list.sort(comparing(Product::getName));
topProducts.addAll(list);
}
return topProducts;
}
public void testReverseComparator() {
Comparator<String> cmpr = Comparator.reverseOrder();
Comparator<String> cmp = cmpr.reversed();
assertEquals(cmp.reversed(), cmpr);
assertEquals(0, cmp.compare("a", "a"));
assertEquals(0, cmpr.compare("a", "a"));
assertTrue(cmp.compare("a", "b") < 0);
assertTrue(cmpr.compare("a", "b") > 0);
assertTrue(cmp.compare("b", "a") > 0);
assertTrue(cmpr.compare("b", "a") < 0);
}
public MetaAccumulator(MetaStackDefinition prefixDefinition, MetaStackDefinition suffixDefinition) {
Objects.requireNonNull(prefixDefinition, "prefixDefinition");
Objects.requireNonNull(suffixDefinition, "suffixDefinition");
this.meta = ArrayListMultimap.create();
this.prefixes = new TreeMap<>(Comparator.reverseOrder());
this.suffixes = new TreeMap<>(Comparator.reverseOrder());
this.prefixDefinition = prefixDefinition;
this.suffixDefinition = suffixDefinition;
this.prefixAccumulator = new MetaStackAccumulator(this.prefixDefinition, ChatMetaType.PREFIX);
this.suffixAccumulator = new MetaStackAccumulator(this.suffixDefinition, ChatMetaType.SUFFIX);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder",
retryAnalyzer = RetryAnalyzer.class)
public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception {
// Get Actual
String query = String.format("SELECT * FROM c ORDER BY c.propInt %s", sortOrder);
// Get Expected
Comparator<Integer> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder();
Comparator<Integer> validatorComparator = Comparator.nullsFirst(order);
List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator);
this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100}, expectedResourceIds);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder")
public void queryDocumentsWithOrderByContinuationTokensString(String sortOrder) throws Exception {
// Get Actual
String query = String.format("SELECT * FROM c ORDER BY c.id %s", sortOrder);
// Get Expected
Comparator<String> order = sortOrder.equals("ASC")?Comparator.naturalOrder():Comparator.reverseOrder();
Comparator<String> validatorComparator = Comparator.nullsFirst(order);
List<String> expectedResourceIds = sortDocumentsAndCollectResourceIds("id", d -> d.getString("id"), validatorComparator);
this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds);
}
public void testReverseComparator() {
Comparator<String> cmpr = Comparator.reverseOrder();
Comparator<String> cmp = cmpr.reversed();
assertEquals(cmp.reversed(), cmpr);
assertEquals(0, cmp.compare("a", "a"));
assertEquals(0, cmpr.compare("a", "a"));
assertTrue(cmp.compare("a", "b") < 0);
assertTrue(cmpr.compare("a", "b") > 0);
assertTrue(cmp.compare("b", "a") > 0);
assertTrue(cmpr.compare("b", "a") < 0);
}
public static <T> Comparator<T> reverseComparator(Comparator<T> cmp) {
assert (cmp == Comparator.naturalOrder() || cmp == Comparator.reverseOrder() || cmp == null);
if (cmp == Comparator.naturalOrder())
return (Comparator<T>) Comparator.reverseOrder();
else if (cmp == Comparator.reverseOrder())
return (Comparator<T>) Comparator.naturalOrder();
else
return null;
}
private TreeFacetField buildOtherNode(Collection<TreeFacetField> otherNodes) {
// Prune the other nodes - use the SimplePruner
SortedSet<TreeFacetField> pruned = new TreeSet<>(Comparator.reverseOrder());
pruned.addAll(new SimplePruner(SimplePruner.MIN_CHILD_COUNT).prune(otherNodes));
TreeFacetField other = new TreeFacetField(moreLabel, "", 0, 0, pruned);
other.recalculateChildCount();
return other;
}
TableResizer(DataSchema dataSchema, AggregationFunction[] aggregationFunctions,
List<OrderByExpressionContext> orderByExpressions) {
// NOTE: the assumption here is that the key columns will appear before the aggregation columns in the data schema
// This is handled in the only in the AggregationGroupByOrderByOperator for now
int numColumns = dataSchema.size();
int numAggregations = aggregationFunctions.length;
int numKeyColumns = numColumns - numAggregations;
Map<String, Integer> columnIndexMap = new HashMap<>();
Map<String, AggregationFunction> aggregationColumnToFunction = new HashMap<>();
for (int i = 0; i < numColumns; i++) {
String columnName = dataSchema.getColumnName(i);
columnIndexMap.put(columnName, i);
if (i >= numKeyColumns) {
aggregationColumnToFunction.put(columnName, aggregationFunctions[i - numKeyColumns]);
}
}
_numOrderByExpressions = orderByExpressions.size();
_orderByValueExtractors = new OrderByValueExtractor[_numOrderByExpressions];
Comparator[] comparators = new Comparator[_numOrderByExpressions];
for (int orderByIdx = 0; orderByIdx < _numOrderByExpressions; orderByIdx++) {
OrderByExpressionContext orderByExpression = orderByExpressions.get(orderByIdx);
String column = orderByExpression.getExpression().toString();
if (columnIndexMap.containsKey(column)) {
int index = columnIndexMap.get(column);
if (index < numKeyColumns) {
_orderByValueExtractors[orderByIdx] = new KeyColumnExtractor(index);
} else {
AggregationFunction aggregationFunction = aggregationColumnToFunction.get(column);
_orderByValueExtractors[orderByIdx] = new AggregationColumnExtractor(index, aggregationFunction);
}
} else {
throw new IllegalStateException("Could not find column " + column + " in data schema");
}
comparators[orderByIdx] = orderByExpression.isAsc() ? Comparator.naturalOrder() : Comparator.reverseOrder();
}
_intermediateRecordComparator = (o1, o2) -> {
for (int i = 0; i < _numOrderByExpressions; i++) {
int result = comparators[i].compare(o1._values[i], o2._values[i]);
if (result != 0) {
return result;
}
}
return 0;
};
}
DateTimeParser(String dateTime, ZonedDateTime baseDateTime) {
this.tokenizer = new DateTimeTokenizer(dateTime);
this.relatives = new PriorityQueue<>(Comparator.reverseOrder()); // process bigger priorities first
this.matched = new ArrayDeque<>();
this.baseDateTime = baseDateTime;
}
public void testReverseOrder() {
List<Item> itemsList = new ArrayList<Item>(Arrays.asList(orderedItems));
Collections.reverse(itemsList);
Comparator<Item> comparator = Comparator.reverseOrder();
checkComparison(comparator, itemsList.toArray(new Item[0]));
}