Java Code Examples for java.util.Comparator#reverseOrder()

The following examples show how to use java.util.Comparator#reverseOrder() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TimerWheelTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 2
Source File: SimplePruner.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: SortAndOrderHelper.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: DirtyLambdas.java    From training with MIT License 5 votes vote down vote up
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;
}
 
Example 5
Source File: DatapointPruner.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: ObjectSequence.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 7
Source File: BasicTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: OrderbyDocumentQueryTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@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);
}
 
Example 9
Source File: OrderbyDocumentQueryTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@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);
}
 
Example 10
Source File: MetaAccumulator.java    From LuckPerms with MIT License 5 votes vote down vote up
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);
}
 
Example 11
Source File: BasicTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: BasicTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: DirtyLambdas.java    From training with MIT License 5 votes vote down vote up
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;
}
 
Example 14
Source File: DirtyLambdas.java    From training with MIT License 5 votes vote down vote up
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;
}
 
Example 15
Source File: BasicTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: BigDecimalStream.java    From big-math with MIT License 5 votes vote down vote up
@Override
public Comparator<? super BigDecimal> getComparator() {
	if (step.signum() < 0) {
		return Comparator.reverseOrder();
	}
	return null;
}
 
Example 17
Source File: Java8ComparatorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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));
}
 
Example 18
Source File: ComparatorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
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]));
}
 
Example 19
Source File: DateTimeParser.java    From jphp with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: TableResizer.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
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;
  };
}