Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor,
        Comparator<? super U> keyComparator) 

Source Link

Document

Accepts a function that extracts a sort key from a type T , and returns a Comparator that compares by that sort key using the specified Comparator .

Usage

From source file:org.openstreetmap.josm.gui.preferences.imagery.CacheContentsPanel.java

public static String[][] getCacheStats(CacheAccess<String, BufferedImageCacheEntry> cache) {
    Set<String> keySet = cache.getCacheControl().getKeySet();
    Map<String, int[]> temp = new ConcurrentHashMap<>(); // use int[] as a Object reference to int, gives better performance
    for (String key : keySet) {
        String[] keyParts = key.split(":", 2);
        if (keyParts.length == 2) {
            int[] counter = temp.get(keyParts[0]);
            if (counter == null) {
                temp.put(keyParts[0], new int[] { 1 });
            } else {
                counter[0]++;//from  w  w  w.  java  2  s .com
            }
        } else {
            Logging.warn("Could not parse the key: {0}. No colon found", key);
        }
    }

    List<Pair<String, Integer>> sortedStats = new ArrayList<>();
    for (Entry<String, int[]> e : temp.entrySet()) {
        sortedStats.add(new Pair<>(e.getKey(), e.getValue()[0]));
    }
    sortedStats.sort(Comparator.comparing(o -> o.b, Comparator.reverseOrder()));
    String[][] ret = new String[sortedStats.size()][3];
    int index = 0;
    for (Pair<String, Integer> e : sortedStats) {
        ret[index] = new String[] { e.a, e.b.toString(), tr("Clear") };
        index++;
    }
    return ret;
}

From source file:com.thinkbiganalytics.metadata.cache.FeedHealthSummaryCache.java

public FeedStatus getUserFeeds(Long time, String feedName) {
    RoleSetExposingSecurityExpressionRoot userContext = feedAclCache.userContext();
    //streamline the summaries as they could have multiple
    Map<String, FeedSummary> latestFeeds = new HashMap<>();

    Comparator<FeedSummary> byRunningStatus = Comparator.comparing(FeedSummary::getRunStatus,
            Comparator.nullsLast(Comparator.naturalOrder()));

    Comparator<FeedSummary> byStartTime = Comparator.comparing(FeedSummary::getStartTime,
            Comparator.nullsLast(Comparator.naturalOrder()));

    getFeedSummaryList(time).stream().filter(
            summary -> (StringUtils.isBlank(feedName) || feedName.equalsIgnoreCase(summary.getFeedName()))
                    && feedAclCache.hasAccess(userContext, summary.getFeedId().toString()))
            .sorted(byRunningStatus.thenComparing(byStartTime)).forEach(f -> {
                String feedId = f.getFeedId().toString();
                if (!latestFeeds.containsKey(feedId)) {
                    latestFeeds.put(feedId, f);
                }/*from   w  w  w. j  a  va 2s  .  c  om*/
            });

    //NOTE it could also populate the last job execution time since the above query gets a union of the running jobs along with the latest finished jobs by feed
    List<FeedHealth> feedSummaryHealth = latestFeeds.values().stream()
            .map(f -> FeedModelTransform.feedHealth(f)).collect(Collectors.toList());
    return FeedModelTransform.feedStatus(feedSummaryHealth);
}

From source file:org.talend.dataprep.util.SortAndOrderHelper.java

/**
 * Return a dataset metadata comparator from the given parameters.
 *
 * @param sortKey  the sort key./*from   ww w. ja v  a 2  s  . c  o m*/
 * @param orderKey the order key to use.
 * @return a dataset metadata comparator from the given parameters.
 */
public static Comparator<DataSetMetadata> getDataSetMetadataComparator(String sortKey, String orderKey) {

    Comparator<String> comparisonOrder = getOrderComparator(orderKey);

    // Select comparator for sort (either by name or date)
    final Comparator<DataSetMetadata> comparator;

    Sort sort;
    try {
        sort = Sort.valueOf(sortKey.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("sort", sortKey));
    }

    switch (sort) {
    case NAME:
        comparator = Comparator.comparing(dataSetMetadata -> dataSetMetadata.getName().toUpperCase(),
                comparisonOrder);
        break;
    case DATE:
        comparator = Comparator.comparing(metadata -> valueOf(metadata.getCreationDate()), comparisonOrder);
        break;
    case MODIF:
        comparator = Comparator.comparing(metadata -> valueOf(metadata.getLastModificationDate()),
                comparisonOrder);
        break;
    default:
        // this should never happen
        throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("sort", sort));
    }
    return comparator;
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.Versions.java

public static Comparator<String> orderBySemVer() {
    Comparator<SemVer> comparator = Comparator.nullsLast(SemVer.comparator());
    return Comparator.comparing(SemVer::fromString, comparator).thenComparing(Comparator.naturalOrder());
}

From source file:org.eclipse.sw360.licenseinfo.outputGenerators.OutputGenerator.java

@NotNull
protected static List<LicenseNameWithText> getSortedLicenseNameWithTexts(
        Collection<LicenseInfoParsingResult> projectLicenseInfoResults) {
    Set<LicenseNameWithText> licenseNamesWithText = projectLicenseInfoResults.stream()
            .map(LicenseInfoParsingResult::getLicenseInfo).filter(Objects::nonNull)
            .map(LicenseInfo::getLicenseNamesWithTexts).filter(Objects::nonNull).reduce(Sets::union)
            .orElse(Collections.emptySet());

    return licenseNamesWithText.stream()
            .filter(licenseNameWithText -> !LicenseNameWithTextUtils.isEmpty(licenseNameWithText))
            .sorted(Comparator.comparing(LicenseNameWithText::getLicenseName, String.CASE_INSENSITIVE_ORDER))
            .collect(Collectors.toList());
}

From source file:org.talend.dataprep.util.SortAndOrderHelper.java

/**
 * Return a Preparation comparator from the given parameters.
 *
 * @param sortKey  the sort key./*from  ww  w  .j a v a2  s. c  o m*/
 * @param orderKey the order comparator to use.
 * @return a preparation comparator from the given parameters.
 */
public static Comparator<Preparation> getPreparationComparator(String sortKey, String orderKey) {

    Comparator<String> comparisonOrder = getOrderComparator(orderKey);

    Sort sort;
    try {
        sort = Sort.valueOf(sortKey.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("sort", sortKey));
    }

    // Select comparator for sort (either by name or date)
    final Comparator<Preparation> comparator;
    switch (sort) {
    case NAME:
        comparator = Comparator.comparing(dataSetMetadata -> dataSetMetadata.getName().toUpperCase(),
                comparisonOrder);
        break;
    case DATE:
        comparator = Comparator.comparing(p -> {
            if (p != null) {
                return String.valueOf(p.getCreationDate());
            } else {
                return StringUtils.EMPTY;
            }
        }, comparisonOrder);
        break;
    case MODIF:
        comparator = Comparator.comparing(p -> {
            if (p != null) {
                return String.valueOf(p.getLastModificationDate());
            } else {
                return StringUtils.EMPTY;
            }
        }, comparisonOrder);
        break;
    default:
        throw new TDPException(ILLEGAL_SORT_FOR_LIST, ExceptionContext.build().put("sort", sort));
    }
    return comparator;
}

From source file:org.nuxeo.ecm.core.storage.dbs.DBSCachingRepository.java

@Override
public List<State> readStates(List<String> ids) {
    ImmutableMap<String, State> statesMap = cache.getAllPresent(ids);
    List<String> idsToRetrieve = new ArrayList<>(ids);
    idsToRetrieve.removeAll(statesMap.keySet());
    // Read missing states from repository
    List<State> states = repository.readStates(idsToRetrieve);
    // Cache them
    states.forEach(this::putInCache);
    // Add previous cached one
    states.addAll(statesMap.values());//from  w  ww.j a v a2s  .c  om
    // Sort them
    states.sort(Comparator.comparing(state -> state.get(KEY_ID).toString(), Ordering.explicit(ids)));
    return states;
}

From source file:org.talend.dataprep.util.SortAndOrderHelper.java

/**
 * Return a Folder comparator from the given parameters.
 *
 * @param sortKey  the sort key./* ww  w.j av a  2 s.  c om*/
 * @param orderKey the order comparator to use.
 * @return a folder comparator from the given parameters.
 */
public static Comparator<Folder> getFolderComparator(String sortKey, String orderKey) {

    Comparator<String> order = getOrderComparator(orderKey);

    Sort sort;
    try {
        sort = Sort.valueOf(sortKey.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new TDPException(CommonErrorCodes.ILLEGAL_ORDER_FOR_LIST, build().put("sort", sortKey));
    }

    // Select comparator for sort (either by name or date)
    final Comparator<Folder> comp;
    switch (sort) {
    case NAME:
        comp = Comparator.comparing(Folder::getName, order);
        break;
    case DATE:
        comp = Comparator.comparing(folder -> String.valueOf(folder.getCreationDate()), order);
        break;
    case MODIF:
        comp = Comparator.comparing(folder -> String.valueOf(folder.getLastModificationDate()), order);
        break;
    default:
        throw new TDPException(ILLEGAL_SORT_FOR_LIST, ExceptionContext.build().put("sort", sort));
    }
    return comp;
}

From source file:com.evolveum.midpoint.wf.impl.processors.primary.policy.ApprovalSchemaBuilder.java

private void processFragmentGroup(List<Fragment> fragments, ApprovalSchemaType resultingSchemaType,
        SchemaAttachedPolicyRulesType attachedRules, ModelInvocationContext ctx, OperationResult result)
        throws SchemaException {
    Fragment firstFragment = fragments.get(0);
    appendAddOnFragments(fragments);// ww  w. j a  v  a2 s .c  om
    List<ApprovalStageDefinitionType> fragmentStageDefs = cloneAndMergeStages(fragments);
    if (fragmentStageDefs.isEmpty()) {
        return; // probably shouldn't occur
    }
    fragmentStageDefs.sort(Comparator.comparing(s -> getNumber(s), Comparator.nullsLast(naturalOrder())));
    RelationResolver relationResolver = primaryChangeAspect.createRelationResolver(firstFragment.target,
            result);
    ReferenceResolver referenceResolver = primaryChangeAspect.createReferenceResolver(ctx.modelContext,
            ctx.taskFromModel, result);
    int from = getStages(resultingSchemaType).size() + 1;
    int i = from;
    for (ApprovalStageDefinitionType stageDef : fragmentStageDefs) {
        stageDef.asPrismContainerValue().setId(null); // to avoid ID collision
        stageDef.setOrder(null);
        stageDef.setNumber(i++);
        approvalSchemaHelper.prepareStage(stageDef, relationResolver, referenceResolver);
        resultingSchemaType.getStage().add(stageDef);
    }
    if (firstFragment.policyRule != null) {
        List<EvaluatedPolicyRuleType> rules = new ArrayList<>();
        firstFragment.policyRule.addToEvaluatedPolicyRuleTypes(rules,
                new PolicyRuleExternalizationOptions(FULL, false, true));
        for (EvaluatedPolicyRuleType rule : rules) {
            SchemaAttachedPolicyRuleType attachedRule = new SchemaAttachedPolicyRuleType();
            attachedRule.setStageMin(from);
            attachedRule.setStageMax(i - 1);
            attachedRule.setRule(rule);
            attachedRules.getEntry().add(attachedRule);
        }
    }
}

From source file:com.evolveum.midpoint.schema.util.WfContextUtil.java

@NotNull
private static List<ApprovalStageDefinitionType> getSortedStages(ApprovalSchemaType schema) {
    List<ApprovalStageDefinitionType> stages = new ArrayList<>(getStages(schema));
    stages.sort(//from   www.j  a  v a 2s. c o m
            Comparator.comparing(stage -> getNumber(stage), Comparator.nullsLast(Comparator.naturalOrder())));
    return stages;
}