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:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importRoomList() {
    this.roomIdToRoomMap = new HashMap<>();
    List<Room> roomList = new ArrayList<>();

    String roomsUrl = conferenceBaseUrl + "/rooms/";
    LOGGER.debug("Sending a request to: " + roomsUrl);
    JsonObject rootObject = readJson(roomsUrl, JsonReader::readObject);

    JsonArray roomArray = rootObject.getJsonArray("rooms");
    for (int i = 0; i < roomArray.size(); i++) {
        JsonObject roomObject = roomArray.getJsonObject(i);
        String id = roomObject.getString("id");
        int capacity = roomObject.getInt("capacity");

        if (!Arrays.asList(IGNORED_ROOM_IDS).contains(id)) {
            Room room = new Room((long) i);
            room.setName(id);/*from w  w w .ja  v  a 2  s  .c o  m*/
            room.setCapacity(capacity);
            room.setTalkTypeSet(getTalkTypeSetForCapacity(capacity));
            for (TalkType talkType : room.getTalkTypeSet()) {
                talkType.getCompatibleRoomSet().add(room);
            }
            room.setTagSet(new HashSet<>());
            room.setUnavailableTimeslotSet(new HashSet<>());
            roomList.add(room);
            roomIdToRoomMap.put(id, room);
        }
    }

    roomList.sort(Comparator.comparing(Room::getName));
    solution.setRoomList(roomList);
}

From source file:io.spring.initializr.generator.CommandLineHelpGenerator.java

protected String generateTypeTable(InitializrMetadata metadata, String linkHeader, boolean addTags) {
    String[][] typeTable = new String[metadata.getTypes().getContent().size() + 1][];
    if (addTags) {
        typeTable[0] = new String[] { linkHeader, "Description", "Tags" };
    } else {/*from  w w  w .j a va 2 s  . co m*/
        typeTable[0] = new String[] { linkHeader, "Description" };
    }
    int i = 1;
    for (Type type : metadata.getTypes().getContent().stream()
            .sorted(Comparator.comparing(MetadataElement::getId)).collect(Collectors.toList())) {
        String[] data = new String[typeTable[0].length];
        data[0] = (type.isDefault() ? type.getId() + " *" : type.getId());
        data[1] = type.getDescription() != null ? type.getDescription() : type.getName();
        if (addTags) {
            data[2] = buildTagRepresentation(type);
        }
        typeTable[i++] = data;
    }
    return TableGenerator.generate(typeTable);
}

From source file:org.mortbay.jetty.load.generator.jenkins.result.LoadResultProjectAction.java

public static List<RunInformations> searchRunInformations(String jettyVersion, ElasticHost elasticHost,
        int maxResult) throws IOException {

    String originalJettyVersion = jettyVersion;

    // jettyVersion 9.4.9*
    //in case jettyVersion is 9.4.9.v20180320 we need to replace with 9.4.9*
    if (StringUtils.contains(jettyVersion, 'v')) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, ".v");
    }//from   ww  w.  j  ava  2s  .  c  o m
    // FIXME investigate elastic but query such 9.4.10-SNAPSHOT doesn't work...
    // so using 9.4.10* then filter response back....
    if (StringUtils.contains(jettyVersion, "-SNAPSHOT")) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, "-SNAPSHOT");
    }

    // in case of 9.4.11-NO-LOGGER-SNAPSHOT still not working with elastic
    // here we must have only number or . so remove everything else

    StringBuilder versionQuery = new StringBuilder();
    CharacterIterator ci = new StringCharacterIterator(jettyVersion);
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        if (NumberUtils.isCreatable(Character.toString(c)) || c == '.') {
            versionQuery.append(c);
        }
    }

    jettyVersion = versionQuery.toString() + "*";

    try (ElasticResultStore elasticResultStore = elasticHost.buildElasticResultStore(); //
            InputStream inputStream = LoadResultProjectAction.class
                    .getResourceAsStream("/versionResult.json")) {
        String versionResultQuery = IOUtils.toString(inputStream);
        Map<String, String> map = new HashMap<>(1);
        map.put("jettyVersion", jettyVersion);
        map.put("maxResult", Integer.toString(maxResult));
        versionResultQuery = StrSubstitutor.replace(versionResultQuery, map);

        String results = elasticResultStore.search(versionResultQuery);

        List<LoadResult> loadResults = ElasticResultStore
                .map(new HttpContentResponse(null, results.getBytes(), null, null));

        List<RunInformations> runInformations = //
                loadResults.stream() //
                        .filter(loadResult -> StringUtils.equalsIgnoreCase(originalJettyVersion, //
                                loadResult.getServerInfo().getJettyVersion())) //
                        .map(loadResult -> new RunInformations(
                                loadResult.getServerInfo().getJettyVersion() + ":"
                                        + loadResult.getServerInfo().getGitHash(), //
                                loadResult.getCollectorInformations(),
                                StringUtils.lowerCase(loadResult.getTransport())) //
                                        .jettyVersion(loadResult.getServerInfo().getJettyVersion()) //
                                        .estimatedQps(LoadTestResultBuildAction.estimatedQps(
                                                LoadTestResultBuildAction.getLoaderConfig(loadResult))) //
                                        .serverInfo(loadResult.getServerInfo())) //
                        .collect(Collectors.toList());

        Collections.sort(runInformations, Comparator.comparing(o -> o.getStartTimeStamp()));
        return runInformations;
    }

}

From source file:org.apache.james.mailbox.cassandra.mail.CassandraMessageMapper.java

@Override
public Iterator<MailboxMessage> findInMailbox(Mailbox mailbox, MessageRange messageRange, FetchType ftype,
        int max) throws MailboxException {
    CassandraId mailboxId = (CassandraId) mailbox.getMailboxId();
    return retrieveMessages(retrieveMessageIds(mailboxId, messageRange), ftype, Optional.of(max)).join()
            .map(SimpleMailboxMessage -> (MailboxMessage) SimpleMailboxMessage)
            .sorted(Comparator.comparing(MailboxMessage::getUid)).iterator();
}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowSummaryTable.java

private void printPrecontingencyViolations(String workflowId, String basecaseId, OnlineDb onlinedb,
        TableFormatter formatter) {/*from  w  w w .java2 s.c o  m*/
    Map<Integer, Map<OnlineStep, List<LimitViolation>>> wfViolations = onlinedb.getViolations(workflowId);
    Map<Integer, ? extends StateProcessingStatus> statesProcessingStatus = onlinedb
            .getStatesProcessingStatus(workflowId);
    if (wfViolations != null && !wfViolations.keySet().isEmpty()) {
        new TreeMap<>(statesProcessingStatus).forEach((stateId, stateprocessingStatus) -> {
            if (stateprocessingStatus != null && stateprocessingStatus.getStatus() != null
                    && !stateprocessingStatus.getStatus().isEmpty()) {
                for (String step : stateprocessingStatus.getStatus().keySet()) {
                    if (OnlineTaskStatus
                            .valueOf(stateprocessingStatus.getStatus().get(step)) == OnlineTaskStatus.FAILED) {
                        try {
                            formatter.writeCell(workflowId);
                            formatter.writeCell(basecaseId);
                            formatter.writeCell(EMPTY_CONTINGENCY_ID);
                            formatter.writeCell(stateId);
                            formatter.writeCell(step);
                            formatter.writeCell(stateprocessingStatus.getDetail());
                            formatter.writeEmptyCell();
                            formatter.writeEmptyCell();
                            formatter.writeEmptyCell();
                            formatter.writeEmptyCell();
                            formatter.writeEmptyCell();
                            formatter.writeEmptyCell();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    }
                }
            }
            Map<OnlineStep, List<LimitViolation>> stateViolations = wfViolations.get(stateId);
            if (stateViolations != null && !stateViolations.keySet().isEmpty()) {
                stateViolations.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                        .forEach(entry -> printViolations(workflowId, basecaseId, EMPTY_CONTINGENCY_ID, stateId,
                                entry.getKey(), entry.getValue(), formatter));
            }
        });
    }
}

From source file:org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrderer.java

public List<String> orderSuggestionsUsingModel(List<String> suggestions, String word, AnalyzedSentence sentence,
        int startPos, int wordLength) {
    if (!isMlAvailable()) {
        return suggestions;
    }/* w ww .  j av a 2s  .  c  o  m*/
    List<Pair<String, Float>> suggestionsScores = new LinkedList<>();
    for (String suggestion : suggestions) {
        String text = sentence.getText();
        String correctedSentence = text.substring(0, startPos) + suggestion
                + sentence.getText().substring(startPos + wordLength);

        float score = processRow(text, correctedSentence, word, suggestion, DEFAULT_CONTEXT_LENGTH);
        suggestionsScores.add(Pair.of(suggestion, score));
    }
    Comparator<Pair<String, Float>> comparing = Comparator.comparing(Pair::getValue);
    suggestionsScores.sort(comparing.reversed());
    List<String> result = new LinkedList<>();
    suggestionsScores.iterator().forEachRemaining((Pair<String, Float> p) -> result.add(p.getKey()));
    return result;
}

From source file:edu.cmu.lti.oaqa.bioqa.providers.kb.TmToolConceptProvider.java

protected List<String> requestConcepts(List<String> normalizedTexts, String trigger)
        throws AnalysisEngineProcessException {
    PubAnnotation[] inputs = PubAnnotationConvertUtil.convertTextsToPubAnnotations(normalizedTexts);
    String request = gson.toJson(inputs, PubAnnotation[].class);
    String response;/*  w ww.j ava 2s . co m*/
    try {
        response = submitText(trigger, request);
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
    PubAnnotation[] outputs = gson.fromJson("[" + response + "]", PubAnnotation[].class);
    List<PubAnnotation> sortedOutputs = Arrays.stream(outputs)
            .sorted(Comparator.comparing(pa -> Integer.parseInt(pa.getSourceid()))).collect(toList());
    List<String> denotationStrings = sortedOutputs.stream().map(PubAnnotation::getDenotations).map(gson::toJson)
            .collect(toList());
    if (denotationStrings.size() != normalizedTexts.size()) {
        throw TmToolConceptProviderException.unequalVolume(trigger, normalizedTexts.size(),
                denotationStrings.size());
    }
    for (int i = 0; i < normalizedTexts.size(); i++) {
        String sentText = normalizedTexts.get(i);
        String recvText = PubAnnotationConvertUtil.normalizeText(sortedOutputs.get(i).getText());
        if (sentText.length() != recvText.length()) {
            throw TmToolConceptProviderException.unequalTextLength(trigger, sentText, recvText);
        }
        //      if (sentText.equals(recvText)) {
        //        throw TmToolConceptProviderException.textChanged(trigger, sentText, recvText);
        //      }
    }
    return denotationStrings;
}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorProjectAction.java

public void doPerFamilyStatusNumber(StaplerRequest req, StaplerResponse rsp)
        throws IOException, ServletException {
    LOGGER.debug("doPerFamilyStatusNumber");

    List<StatusResult> statusResults = new ArrayList<>();

    for (Run run : this.builds) {
        LoadGeneratorBuildAction buildAction = run.getAction(LoadGeneratorBuildAction.class);
        if (buildAction != null) {
            Map<Integer, LongAdder> re = buildAction.getResponseNumberPerStatusFamily();
            if (re != null) {
                StatusResult statusResult = new StatusResult();
                statusResult.buildId = run.getId();
                if (re.get(1) != null) {
                    statusResult._1xx = re.get(1).longValue();
                }//from  ww w .j a  v a2  s.c om
                if (re.get(2) != null) {
                    statusResult._2xx = re.get(2).longValue();
                }
                if (re.get(3) != null) {
                    statusResult._3xx = re.get(3).longValue();
                }
                if (re.get(4) != null) {
                    statusResult._4xx = re.get(4).longValue();
                }
                if (re.get(5) != null) {
                    statusResult._5xx = re.get(5).longValue();
                }
                statusResults.add(statusResult);
            }
        }
    }

    Collections.sort(statusResults, Comparator.comparing(StatusResult::getBuildId));

    StringWriter stringWriter = new StringWriter();

    new ObjectMapper() //
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) //
            .writeValue(stringWriter, statusResults);

    rsp.getWriter().write(stringWriter.toString());
}

From source file:controllers.config.Config.java

private void overlayHostclass(final HostclassOutput hostclassOutput, final Hostclass hostclass) {
    final ImmutableMap<String, HostclassOutput.Package> oldPackageMap = Maps
            .uniqueIndex(hostclassOutput.getPackages().getProduction(), HostclassOutput.Package::getName);
    final Map<String, HostclassOutput.Package> newPackages = Maps.newHashMap(oldPackageMap);

    final ImmutableMap<String, HostclassOutput.Package> oldFailsafeMap = Maps
            .uniqueIndex(hostclassOutput.getPackages().getFailsafe(), HostclassOutput.Package::getName);
    final Map<String, HostclassOutput.Package> newFailsafe = Maps.newHashMap(oldFailsafeMap);

    final List<Stage> stages = Stage.getStagesForHostclass(hostclass);
    for (final Stage stage : stages) {
        final ManifestHistory snapshot = ManifestHistory.getCurrentForStage(stage);
        if (snapshot == null) {
            LOGGER.warn("snapshot for stage " + stage.getName() + "[" + stage.getId() + "] was null");
            continue;
        }//from  ww w  . j  ava 2s  .c  o m
        final Manifest manifest = snapshot.getManifest();
        for (final PackageVersion aPackage : manifest.getPackages()) {
            newPackages.put(aPackage.getPkg().getName(), new HostclassOutput.Package(
                    String.format("%s-%s", aPackage.getPkg().getName(), aPackage.getVersion())));
        }
        if (!Strings.isNullOrEmpty(snapshot.getConfig())) {
            injectConfig(snapshot, hostclassOutput);
        }
    }
    if (stages.size() > 0) {
        Configuration.root().getStringList("package.overlay").stream().map(HostclassOutput.Package::new)
                .forEach(p -> {
                    newPackages.put(p.getName(), p);
                    newFailsafe.put(p.getName(), p);
                });
    }
    final ArrayList<HostclassOutput.Package> packageList = Lists.newArrayList(newPackages.values());
    Collections.sort(packageList, Comparator.comparing(HostclassOutput.Package::getName));
    hostclassOutput.getPackages().setProduction(Sets.newLinkedHashSet(packageList));

    final ArrayList<HostclassOutput.Package> failsafeList = Lists.newArrayList(newFailsafe.values());
    Collections.sort(failsafeList, Comparator.comparing(HostclassOutput.Package::getName));
    hostclassOutput.getPackages().setFailsafe(Sets.newLinkedHashSet(failsafeList));
}

From source file:org.dcache.util.collector.pools.PoolInfoCollectorUtils.java

/**
 * <p>Accesses current state of selection unit.</p>
 */// w w w.  j  av a  2  s .  c om
public static String[] listGroups(PoolSelectionUnit poolSelectionUnit) {
    if (poolSelectionUnit == null) {
        return new String[0];
    }

    return poolSelectionUnit.getPoolGroups().values().stream()
            .sorted(Comparator.comparing(SelectionPoolGroup::getName)).map(SelectionPoolGroup::getName)
            .toArray(String[]::new);
}