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

The following examples show how to use java.util.Comparator#comparing() . 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: ComparatorRSQLNodeTraveller.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Override
public Comparator<DTO> visit(ComparisonNode node) {
    logger.trace("Sorting direction - {}, arguments {}", node.getOperator(), node.getArguments());
    Comparator<DTO> comparator = null;
    for (String argument : node.getArguments()) {
        Comparator<DTO> comp = Comparator.comparing(dto -> getProperty(dto, argument));
        if (comparator == null) {
            comparator = comp;
        } else {
            comparator = comparator.thenComparing(comp);
        }
    }
    if (comparator == null) {
        throw new RSQLException("No argument for RSQL comparsion found.");
    }
    if (node.getOperator().equals(DESC)) {
        comparator = comparator.reversed();
    }

    return comparator;
}
 
Example 2
Source File: BasicTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void testComparatorDefaultMethods() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    // reverseOrder
    assertComparison(cmp.reversed(), people[1], people[0]);
    // thenComparing(Comparator)
    assertComparison(cmp.thenComparing(cmp2), people[0], people[1]);
    assertComparison(cmp.thenComparing(cmp2), people[4], people[0]);
    // thenComparing(Function)
    assertComparison(cmp.thenComparing(People::getLastName), people[0], people[1]);
    assertComparison(cmp.thenComparing(People::getLastName), people[4], people[0]);
    // thenComparing(ToIntFunction)
    assertComparison(cmp.thenComparingInt(People::getAge), people[0], people[1]);
    assertComparison(cmp.thenComparingInt(People::getAge), people[1], people[5]);
    // thenComparing(ToLongFunction)
    assertComparison(cmp.thenComparingLong(People::getAgeAsLong), people[0], people[1]);
    assertComparison(cmp.thenComparingLong(People::getAgeAsLong), people[1], people[5]);
    // thenComparing(ToDoubleFunction)
    assertComparison(cmp.thenComparingDouble(People::getAgeAsDouble), people[0], people[1]);
    assertComparison(cmp.thenComparingDouble(People::getAgeAsDouble), people[1], people[5]);
}
 
Example 3
Source File: LabelModel.java    From pyramid with Apache License 2.0 6 votes vote down vote up
public LabelModel(IMLGradientBoosting boosting, int classIndex) {
    labelName = boosting.getLabelTranslator().toExtLabel(classIndex);
    List<Regressor> regressors = boosting.getRegressors(classIndex);
    List<GeneralTreeRule> allRules = new ArrayList<>();
    for (Regressor regressor : regressors) {
        if (regressor instanceof ConstantRegressor) {
            this.priorSccore = ((ConstantRegressor)regressor).getScore();
        }

        if (regressor instanceof RegressionTree) {
            RegressionTree tree = (RegressionTree) regressor;
            allRules.addAll(tree.getRules());
        }
    }
    Comparator<GeneralTreeRule> comparator = Comparator.comparing(decision -> Math.abs(decision.getScore()));
    rules = GeneralTreeRule.merge(allRules).stream().sorted(comparator.reversed())
            .collect(Collectors.toList());
}
 
Example 4
Source File: ManufOrderWorkflowService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get a list of operation orders sorted by priority and id from the specified manufacturing
 * order.
 *
 * @param manufOrder
 * @return
 */
protected List<OperationOrder> getSortedOperationOrderList(ManufOrder manufOrder) {
  List<OperationOrder> operationOrderList =
      MoreObjects.firstNonNull(manufOrder.getOperationOrderList(), Collections.emptyList());
  Comparator<OperationOrder> byPriority =
      Comparator.comparing(
          OperationOrder::getPriority, Comparator.nullsFirst(Comparator.naturalOrder()));
  Comparator<OperationOrder> byId =
      Comparator.comparing(
          OperationOrder::getId, Comparator.nullsFirst(Comparator.naturalOrder()));

  return operationOrderList
      .stream()
      .sorted(byPriority.thenComparing(byId))
      .collect(Collectors.toList());
}
 
Example 5
Source File: DataSet.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
public DataSet(LoadContext context, GameMode gameMode, ListFacade<Campaign> campaigns)
{
	unsortedRaces = new DefaultListFacade<>();
	races = new SortedListFacade<>(new RaceComparator(), unsortedRaces);
	unsortedClasses = new DefaultListFacade<>();
	classes = new SortedListFacade<>(new PCClassComparator(), unsortedClasses);
	deities = new DefaultListFacade<>();
	skills = new DefaultListFacade<>();
	templates = new DefaultListFacade<>();
	unsortedAlignments = new DefaultListFacade<>();
	alignments = new SortedListFacade<>(Comparator.comparing(SortKeyRequired::getSortKey), unsortedAlignments);
	unsortedStats = new DefaultListFacade<>();
	stats = new SortedListFacade<>(Comparator.comparing(SortKeyRequired::getSortKey), unsortedStats);
	abilityMap = new AbilityMap();
	bodyStructures = new DefaultListFacade<>();
	equipment = new DefaultListFacade<>();
	xpTableNames = new DefaultListFacade<>();
	characterTypes = new DefaultListFacade<>();
	kits = new DefaultListFacade<>();
	unsortedSizes = new DefaultListFacade<>();
	sizes = new SortedListFacade<>(Comparator.comparing(size -> size.getSafe(IntegerKey.SIZEORDER)), unsortedSizes);
	this.context = context;
	this.gameMode = gameMode;
	this.campaigns = campaigns;
	initLists();
}
 
Example 6
Source File: EntryComparators.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testKVComparators() {
    // Comparator<People> cmp = Comparator.naturalOrder(); // Should fail to compiler as People is not comparable
    // We can use simple comparator, but those have been tested above.
    // Thus choose to do compose for some level of interation.
    Comparator<People> cmp1 = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    Comparator<People> cmp = cmp1.thenComparing(cmp2);

    assertPairComparison(people[0], people[0], people[1], people[1],
                     Map.Entry.<People, People>comparingByKey(cmp),
                     Map.Entry.<People, People>comparingByValue(cmp));

}
 
Example 7
Source File: Java8ComparatorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenNullsLast_thenSortedByNameWithNullsLast() {
    Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
    Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
    Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
    // System.out.println(Arrays.toString(employeesArrayWithNulls));
    assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
}
 
Example 8
Source File: ArgSort.java    From pyramid with Apache License 2.0 5 votes vote down vote up
public static int[] argSortAscending(double[] arr){
    Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
    return IntStream.range(0,arr.length)
            .mapToObj(i-> new Pair<>(i,arr[i]))
            .sorted(comparator)
            .mapToInt(Pair::getFirst).toArray();
}
 
Example 9
Source File: SortingIT.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void runTestWithStringValues(final SortOption sortOption,
        final Function<String, Thing> thingBuilder,
        final Collection<String> values) {

    final List<Thing> things = createAndPersistThings(values, thingBuilder);
    final Comparator<Thing> ascendingComparator =
            Comparator.comparing(extractStringField(sortOption.getSortExpression()));

    runInternallyWithThings(sortOption, things, ascendingComparator);
}
 
Example 10
Source File: CTAT.java    From pyramid with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param predictionResults pair of (confidence, correctness)
 * @return
 */
public static AllThresholdResult showAllThresholds(List<Pair<Double,Double>> predictionResults){
    Comparator<Pair<Double,Double>> comparator = Comparator.comparing(Pair::getFirst);
    List<Pair<Double,Double>> sorted = predictionResults.stream().sorted(comparator.reversed()).collect(Collectors.toList());


    double total = 0;
    double correct = 0;
    List<Double> thresholds = new ArrayList<>();
    List<Double> accuracies = new ArrayList<>();
    List<Double> fractions = new ArrayList<>();
    for (int i=0;i<sorted.size();i++){
        Pair<Double,Double> pair = sorted.get(i);
        total+=1;
        correct += pair.getSecond();

        double current = pair.getFirst();
        if ((i<sorted.size()-1&&!sorted.get(i).getFirst().equals(sorted.get(i+1).getFirst()))||i==sorted.size()-1){
            thresholds.add(current);
            accuracies.add(correct*1.0/total);
            fractions.add(total/predictionResults.size());
        }
    }

    Collections.reverse(thresholds);
    Collections.reverse(accuracies);
    Collections.reverse(fractions);


    List<Double> interpolatedAccuracies = interpolatedAccuracies(accuracies);

    AllThresholdResult allThresholdResult = new AllThresholdResult();
    allThresholdResult.accuracies = accuracies;
    allThresholdResult.thresholds = thresholds;
    allThresholdResult.interpolatedAccuracies = interpolatedAccuracies;
    allThresholdResult.percentages=fractions;
    return allThresholdResult;
}
 
Example 11
Source File: SortAndOrderHelper.java    From data-prep with Apache License 2.0 5 votes vote down vote up
/**
 * Return a Folder comparator from the given parameters.
 *
 * @param sortKey  the sort key.
 * @param orderKey the order comparator to use.
 * @return a folder comparator from the given parameters.
 */
public static Comparator<Folder> getFolderComparator(Sort sortKey, Order orderKey) {
    Comparator<Comparable> order = getOrderComparator(orderKey);

    // Select comparator for sort (either by name or date)
    Function<Folder, Comparable> keyExtractor;
    if (sortKey == null) { // default to NAME sort
        keyExtractor = SortAndOrderHelper::extractFolderName;
    } else {
        switch (sortKey) {
        // In case of API call error, default to NAME sort
        case AUTHOR:
        case DATASET_NAME:
        case NB_RECORDS:
        case NB_STEPS:
        case NAME:
            keyExtractor = SortAndOrderHelper::extractFolderName;
            break;
        case CREATION_DATE:
        case DATE:
            keyExtractor = Folder::getCreationDate;
            break;
        case LAST_MODIFICATION_DATE:
            keyExtractor = Folder::getLastModificationDate;
            break;
        default:
            // this should not be possible
            throw new TDPException(ILLEGAL_SORT_FOR_LIST, build().put("sort", sortKey));
        }
    }
    return Comparator.comparing(keyExtractor, order);
}
 
Example 12
Source File: ArgSort.java    From pyramid with Apache License 2.0 5 votes vote down vote up
public static int[] argSortAscending(List<Double> arr){
    Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
    return IntStream.range(0,arr.size())
            .mapToObj(i-> new Pair<>(i,arr.get(i)))
            .sorted(comparator)
            .mapToInt(Pair::getFirst).toArray();
}
 
Example 13
Source File: PriorityQueueToStreamTest.java    From articles with Apache License 2.0 5 votes vote down vote up
@Test
void shouldMaintainInsertionOrder() {
    PriorityQueue<String> queue = new PriorityQueue<>(Comparator.comparing(String::length));
    List<String> content = Arrays.asList("1", "333", "22", "55555", "4444");
    queue.addAll(content);

    assertThat(queue.stream())
      .containsExactlyElementsOf(content);
}
 
Example 14
Source File: CassandraConnectorDatabaseService.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<QualifiedName> listNames(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final QualifiedName name,
    @Nullable final QualifiedName prefix,
    @Nullable final Sort sort,
    @Nullable final Pageable pageable
) {
    log.debug("Attempting to list keyspaces for request {}", context);
    try {
        final List<QualifiedName> names = Lists.newArrayList();
        for (final KeyspaceMetadata keyspace : this.getCluster().getMetadata().getKeyspaces()) {
            final String keyspaceName = keyspace.getName();
            if (prefix != null && !keyspaceName.startsWith(prefix.getDatabaseName())) {
                continue;
            }
            names.add(QualifiedName.ofDatabase(name.getCatalogName(), keyspaceName));
        }

        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            ConnectorUtils.sort(names, sort, comparator);
        }

        final List<QualifiedName> results = ConnectorUtils.paginate(names, pageable);
        log.debug("Finished listing keyspaces for request {}", context);
        return results;
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
 
Example 15
Source File: BasicTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void testComparing() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, 0.0, stringValues[i]);
    Comparator<Thing> comp = Comparator.comparing(new Function<Thing, String>() {
        @Override
        public String apply(Thing thing) {
            return thing.getStringField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 16
Source File: MNVRegionValidator.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private static Comparator<Map.Entry<PotentialMNV, MNVScore>> mnvEntryComparator() {
    final Comparator<Map.Entry<PotentialMNV, MNVScore>> sizeComparator =
            Comparator.comparing(mnvEntry -> mnvEntry.getKey().variants().size());
    final Comparator<Map.Entry<PotentialMNV, MNVScore>> frequencyComparator =
            Comparator.comparing(mnvEntry -> mnvEntry.getValue().frequency());
    final Comparator<Map.Entry<PotentialMNV, MNVScore>> startPositionComparator =
            Comparator.comparing(mnvEntry -> mnvEntry.getKey().start());
    return sizeComparator.reversed().thenComparing(frequencyComparator.reversed()).thenComparing(startPositionComparator);
}
 
Example 17
Source File: MySqlConnectorDatabaseService.java    From metacat with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<QualifiedName> listNames(
    @Nonnull final ConnectorRequestContext context,
    @Nonnull final QualifiedName name,
    @Nullable final QualifiedName prefix,
    @Nullable final Sort sort,
    @Nullable final Pageable pageable
) {
    // Overrides the super class due to MySQL using catalog instead of schemas when trying to list database names
    final String catalogName = name.getCatalogName();
    log.debug("Beginning to list database names for catalog {} for request {}", catalogName, context);

    try (
        final Connection connection = this.getDataSource().getConnection();
        final ResultSet schemas = connection.getMetaData().getCatalogs()
    ) {
        final List<QualifiedName> names = Lists.newArrayList();
        while (schemas.next()) {
            final String schemaName = schemas.getString("TABLE_CAT").toLowerCase(Locale.ENGLISH);
            // skip internal schemas
            if (!schemaName.equals("information_schema") && !schemaName.equals("mysql")) {
                if (prefix == null) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                } else if (StringUtils.isNotBlank(prefix.getDatabaseName())
                    && schemaName.startsWith(prefix.getDatabaseName())) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                }
            }
        }

        // Does user want sorting?
        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            JdbcConnectorUtils.sort(names, sort, comparator);
        }

        // Does user want pagination?
        final List<QualifiedName> results = JdbcConnectorUtils.paginate(names, pageable);

        log.debug("Finished listing database names for catalog {} for request {}", catalogName, context);
        return results;
    } catch (final SQLException se) {
        log.debug("An exception occurred listing database names for catalog {} for request {}",
            catalogName, context, se);
        throw this.getExceptionMapper().toConnectorException(se, name);
    }
}
 
Example 18
Source File: BuildCmd.java    From product-microgateway with Apache License 2.0 4 votes vote down vote up
private void sortFilterBasedOnPosition(ContainerConfig containerConfig) {
    if (containerConfig.getFilters() != null) {
        Comparator<Filter> compareByPosition = Comparator.comparing(Filter::getPosition);
        Collections.sort(containerConfig.getFilters(), compareByPosition);
    }
}
 
Example 19
Source File: SdxRuntimeUpgradeService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Comparator<ImageInfoV4Response> getComparator() {
    return Comparator.comparing(ImageInfoV4Response::getCreated);
}
 
Example 20
Source File: AcademicDecorator.java    From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License 4 votes vote down vote up
public List<Discipline> getDisciplinesByCourse (Course course) {
	List<Discipline> disciplines = academicFacade.getDisciplinesByCourse (course);
	Comparator<Discipline> comp = Comparator.comparing (d->d.getName());
	disciplines.sort (comp);
	return disciplines;
}