java.util.Comparator#comparing ( )源码实例Demo

下面列出了java.util.Comparator#comparing ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: pyramid   文件: LabelModel.java
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());
}
 
/**
 * 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());
}
 
源代码3 项目: pcgen   文件: DataSet.java
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();
}
 
源代码4 项目: openjdk-jdk8u-backup   文件: BasicTest.java
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]);
}
 
源代码5 项目: pnc   文件: ComparatorRSQLNodeTraveller.java
@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;
}
 
源代码6 项目: data-prep   文件: SortAndOrderHelper.java
/**
 * 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);
}
 
源代码7 项目: hmftools   文件: MNVRegionValidator.java
@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);
}
 
源代码8 项目: openjdk-jdk8u   文件: BasicTest.java
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);
}
 
/**
 * {@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);
    }
}
 
源代码10 项目: articles   文件: PriorityQueueToStreamTest.java
@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);
}
 
源代码11 项目: pyramid   文件: ArgSort.java
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();
}
 
源代码12 项目: openjdk-jdk9   文件: EntryComparators.java
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));

}
 
源代码13 项目: pyramid   文件: CTAT.java
/**
 *
 * @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;
}
 
源代码14 项目: ditto   文件: SortingIT.java
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);
}
 
源代码15 项目: pyramid   文件: ArgSort.java
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();
}
 
源代码16 项目: tutorials   文件: Java8ComparatorUnitTest.java
@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));
}
 
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;
}
 
源代码18 项目: metacat   文件: MySqlConnectorDatabaseService.java
/**
 * {@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);
    }
}
 
源代码19 项目: product-microgateway   文件: BuildCmd.java
private void sortFilterBasedOnPosition(ContainerConfig containerConfig) {
    if (containerConfig.getFilters() != null) {
        Comparator<Filter> compareByPosition = Comparator.comparing(Filter::getPosition);
        Collections.sort(containerConfig.getFilters(), compareByPosition);
    }
}
 
源代码20 项目: cloudbreak   文件: SdxRuntimeUpgradeService.java
private Comparator<ImageInfoV4Response> getComparator() {
    return Comparator.comparing(ImageInfoV4Response::getCreated);
}