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 extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:Main.java

/**
 * Sorts a Map by it's value/*from   ww w. j a  v a 2  s  .c o m*/
 *
 * @param map Map
 * @param <K> Key
 * @param <V> Value
 * @return The sorted map
 */
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    Stream<Map.Entry<K, V>> st = map.entrySet().stream();

    st.sorted(Comparator.comparing(Map.Entry::getValue))
            .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));

    return result;
}

From source file:jease.cms.service.Informatons.java

public static Map<Class<?>, Integer> getDatabaseClassCount() {
    Map<Class<?>, Integer> resultMap = new TreeMap<>(Comparator.comparing(Class::getName));
    for (Persistent obj : Database.query(Persistent.class)) {
        Class<?> clazz = obj.getClass();
        if (!resultMap.containsKey(clazz)) {
            resultMap.put(clazz, 0);/*from w w  w . j  a va  2s . c  om*/
        }
        resultMap.put(clazz, resultMap.get(clazz) + 1);
    }
    return resultMap;
}

From source file:com.simiacryptus.text.LanguageModel.java

/**
 * Match language model./*from ww  w.  j a v  a  2 s .  com*/
 *
 * @param text the text
 * @return the language model
 */
public static LanguageModel match(String text) {
    return Arrays.stream(LanguageModel.values())
            .min(Comparator.comparing(model -> model.getTrie().getCodec().encodePPM(text, 2).bitLength)).get();
}

From source file:org.openhab.binding.dwdunwetter.internal.data.SeverityComparator.java

@Override
public int compare(DwdWarningData o1, DwdWarningData o2) {

    Comparator.comparingInt(d -> ((DwdWarningData) d).getSeverity().getOrder());
    Comparator.comparing(DwdWarningData::getOnset);

    int result = Integer.compare(o1.getSeverity().getOrder(), o2.getSeverity().getOrder());
    if (result == 0) {
        result = ObjectUtils.compare(o1.getOnset(), o2.getOnset());
    }// w  w  w . ja  va  2s  . c om
    return result;
}

From source file:com.hubrick.vertx.s3.util.UrlEncodingUtils.java

public static String addParamsSortedToUrl(String url, Map<String, String> params) {
    checkNotNull(url, "url must not be null");
    checkNotNull(!url.isEmpty(), "url must not be empty");
    checkNotNull(params, "params must not be null");
    checkNotNull(!params.isEmpty(), "params must not be empty");

    final String baseUrl = extractBaseUrl(url);
    final String urlParams = baseUrl.equals(url) ? "" : url.replace(baseUrl + "?", "");
    final List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(urlParams, Charsets.UTF_8);

    for (Map.Entry<String, String> paramToUrlEncode : params.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getKey)).collect(Collectors.toList())) {
        nameValuePairs.add(new BasicNameValuePair(paramToUrlEncode.getKey(), paramToUrlEncode.getValue()));
    }//  w w  w . ja v a 2  s . c o  m

    return baseUrl + "?" + URLEncodedUtils.format(nameValuePairs, Charsets.UTF_8);
}

From source file:org.opencb.commons.utils.CommandLineUtils.java

public static void printCommandUsage(JCommander commander, PrintStream printStream) {

    Integer paramNameMaxSize = Math.max(commander.getParameters().stream().map(pd -> pd.getNames().length())
            .collect(Collectors.maxBy(Comparator.naturalOrder())).orElse(20), 20);
    Integer typeMaxSize = Math.max(commander.getParameters().stream().map(pd -> getType(pd).length())
            .collect(Collectors.maxBy(Comparator.naturalOrder())).orElse(10), 10);

    int nameAndTypeLength = paramNameMaxSize + typeMaxSize + 8;
    int maxLineLength = nameAndTypeLength + DESCRIPTION_LENGTH; //160

    Comparator<ParameterDescription> parameterDescriptionComparator = Comparator
            .comparing((ParameterDescription p) -> p.getDescription().contains("DEPRECATED"))
            .thenComparing(ParameterDescription::getLongestName);
    commander.getParameters().stream().sorted(parameterDescriptionComparator).forEach(parameterDescription -> {
        if (parameterDescription.getParameter() != null && !parameterDescription.getParameter().hidden()) {
            String type = getType(parameterDescription);
            String defaultValue = "";
            if (parameterDescription.getDefault() != null) {
                if (parameterDescription.isDynamicParameter()) {
                    Object def = parameterDescription.getDefault();
                    if (def instanceof Map && !((Map) def).isEmpty()) {
                        defaultValue = " [" + def + "]";
                    }/*from w w  w. j a  va2s  .  c  om*/
                } else {
                    defaultValue = " [" + parameterDescription.getDefault() + "]";
                }
            }
            String usage = String.format("%5s %-" + paramNameMaxSize + "s %-" + typeMaxSize + "s %s%s\n",
                    (parameterDescription.getParameterized().getParameter() != null
                            && parameterDescription.getParameterized().getParameter().required()) ? "*" : "",
                    parameterDescription.getNames(), type, parameterDescription.getDescription(), defaultValue);

            // if lines are longer than the maximum they are trimmed and printed in several lines
            List<String> lines = new LinkedList<>();
            while (usage.length() > maxLineLength + 1) {
                int splitPosition = Math.min(1 + usage.lastIndexOf(" ", maxLineLength), usage.length());
                if (splitPosition <= nameAndTypeLength + DESCRIPTION_INDENT) {
                    splitPosition = Math.min(1 + usage.indexOf(" ", maxLineLength), usage.length());
                }
                lines.add(usage.substring(0, splitPosition) + "\n");
                usage = String.format("%" + (nameAndTypeLength + DESCRIPTION_INDENT) + "s", "") + ""
                        + usage.substring(splitPosition);
            }
            // this is empty for short lines and so no prints anything
            lines.forEach(printStream::print);
            // in long lines this prints the last trimmed line
            printStream.print(usage);
        }
    });
}

From source file:com.wrmsr.kleist.Index.java

@JsonCreator
public Index(@JsonProperty("segments") Map<String, Segment> segments) {
    this.segments = segments.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue().getGeneration()))
            .collect(toLinkedHashMap());
    checkArgument(// w  w w  .  j a  v  a 2s  .c o m
            this.segments.values().stream().map(Segment::getGeneration).distinct().count() == segments.size());
}

From source file:TwitterClustering.java

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    Stream<Map.Entry<K, V>> st = map.entrySet().stream();

    st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));

    return result;
}

From source file:org.apache.servicecomb.it.ITUtils.java

public static Map<String, MicroserviceInstance> waitMicroserviceReadyAndLimit(String appId,
        String microserviceName, String strVersionRule, int minInstanceCount) {
    Map<String, MicroserviceInstance> instances = waitMicroserviceReady(appId, microserviceName, strVersionRule,
            minInstanceCount);//from w  ww.j a va2 s  . c  o  m
    return instances.values().stream().sorted(Comparator.comparing(MicroserviceInstance::getInstanceId))
            .limit(minInstanceCount)
            .collect(Collectors.toMap(MicroserviceInstance::getInstanceId, Function.identity()));
}

From source file:io.github.resilience4j.circuitbreaker.monitoring.endpoint.CircuitBreakerEventsEndpoint.java

@ReadOperation
public CircuitBreakerEventsEndpointResponse getAllCircuitBreakerEvents() {
    return new CircuitBreakerEventsEndpointResponse(
            eventConsumerRegistry.getAllEventConsumer().flatMap(CircularEventConsumer::getBufferedEvents)
                    .sorted(Comparator.comparing(CircuitBreakerEvent::getCreationTime))
                    .map(CircuitBreakerEventDTOFactory::createCircuitBreakerEventDTO).toJavaList());
}