Example usage for java.util Comparator comparingInt

List of usage examples for java.util Comparator comparingInt

Introduction

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

Prototype

public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) 

Source Link

Document

Accepts a function that extracts an int sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.apache.commons.rng.examples.jpms.app.DiceGameApplication.java

/**
 * Display the list of players in decreasing order of scores.
 *
 * @param scores Scores returned by {@link #play()}.
 * @return a text diplaying the result of the game.
 */// ww  w .j a  va2 s . c o m
private static String display(int[] scores) {
    final int[][] a = new int[scores.length][2];
    for (int i = 0; i < scores.length; i++) {
        a[i][0] = i;
        a[i][1] = scores[i];
    }
    Arrays.sort(a, Comparator.comparingInt(x -> -x[1]));

    final StringBuilder result = new StringBuilder();
    for (int i = 0; i < scores.length; i++) {
        result.append("Player ").append(a[i][0] + 1).append(" has ").append(a[i][1]).append(" points")
                .append(LINE_SEP);
    }

    return result.toString();
}

From source file:org.apache.james.blob.cassandra.CassandraBlobsDAO.java

private Mono<Integer> saveBlobParts(byte[] data, BlobId blobId) {
    Stream<Pair<Integer, ByteBuffer>> chunks = dataChunker.chunk(data, configuration.getBlobPartSize());
    return Flux.fromStream(chunks).publishOn(Schedulers.elastic(), PREFETCH)
            .flatMap(pair -> writePart(pair.getValue(), blobId, getChunkNum(pair)))
            .collect(Collectors.maxBy(Comparator.comparingInt(x -> x))).flatMap(Mono::justOrEmpty)
            .map(this::numToCount).defaultIfEmpty(0);
}

From source file:org.apache.nifi.minifi.bootstrap.util.ConfigTransformerTest.java

private static void checkOrderOfChildren(Element element, Map<String, Integer> orderMap) {
    int elementOrderList = 0;
    NodeList childNodes = element.getChildNodes();
    String lastOrderedElementName = null;
    for (int i = 0; i < childNodes.getLength(); i++) {
        String nodeName = childNodes.item(i).getNodeName();
        Integer index = orderMap.get(nodeName);
        if (index != null) {
            if (elementOrderList > index) {
                fail("Found " + nodeName + " after " + lastOrderedElementName + "; expected all " + nodeName
                        + " elements to come before the following elements: "
                        + orderMap.entrySet().stream().filter(e -> e.getValue() > index)
                                .sorted(Comparator.comparingInt(e -> e.getValue())).map(e -> e.getKey())
                                .collect(Collectors.joining(", ")));
            }/*from  w  w w. j  a  va  2  s . c o m*/
            lastOrderedElementName = nodeName;
            elementOrderList = index;
        }
    }
}

From source file:org.b3log.solo.service.DataModelService.java

/**
 * Fills tags.//from   w w  w.  j  a  va2s. com
 *
 * @param dataModel data model
 * @throws ServiceException service exception
 */
public void fillTags(final Map<String, Object> dataModel) throws ServiceException {
    Stopwatchs.start("Fill Tags");
    try {
        final List<JSONObject> tags = tagQueryService.getTags();
        tagQueryService.removeForUnpublishedArticles(tags);
        Collections.sort(tags, Comparator.comparingInt(t -> -t.optInt(Tag.TAG_REFERENCE_COUNT)));
        dataModel.put(Tag.TAGS, tags);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Fills tags failed", e);

        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }

    Stopwatchs.end();
}

From source file:org.cloudsimplus.sla.responsetime.CloudletResponseTimeMinimizationExperiment.java

private void printVmsCpuUsage(EventInfo eventInfo) {
    DatacenterBroker broker0 = getFirstBroker();
    broker0.getVmsCreatedList().sort(Comparator.comparingInt(Vm::getId));

    broker0.getVmsCreatedList()/*w  w w.j a v  a  2 s .  c om*/
            .forEach(vm -> Log.printFormattedLine("####Time %.0f: Vm %d CPU usage: %.2f. SLA: %.2f.\n",
                    eventInfo.getTime(), vm.getId(), vm.getCurrentCpuPercentUse(), cpuUtilizationSlaContract));
}

From source file:org.cloudsimplus.sla.responsetime.CloudletResponseTimeMinimizationExperiment.java

/**
* Selects a VM to run a Cloudlet that will minimize the Cloudlet response
* time.//from  ww  w.  j av a 2s.c o  m
*
* @param cloudlet the Cloudlet to select a VM to
* @return the selected Vm
*/
private Vm selectVmForCloudlet(Cloudlet cloudlet) {
    List<Vm> createdVms = cloudlet.getBroker().getVmsCreatedList();
    Log.printLine("\t\tCreated VMs: " + createdVms);
    Comparator<Vm> sortByNumberOfFreePes = Comparator.comparingInt(vm -> getExpectedNumberOfFreeVmPes(vm));
    Comparator<Vm> sortByExpectedCloudletResponseTime = Comparator
            .comparingDouble(vm -> getExpectedCloudletResponseTime(cloudlet, vm));
    createdVms.sort(sortByNumberOfFreePes.thenComparing(sortByExpectedCloudletResponseTime).reversed());
    Vm mostFreePesVm = createdVms.stream().findFirst().orElse(Vm.NULL);

    Vm selectedVm = createdVms.stream()
            .filter(vm -> getExpectedNumberOfFreeVmPes(vm) >= cloudlet.getNumberOfPes())
            .filter(vm -> getExpectedCloudletResponseTime(cloudlet, vm) <= responseTimeSlaContract).findFirst()
            .orElse(mostFreePesVm);

    return selectedVm;
}

From source file:org.dspace.content.RelationshipServiceImpl.java

@Override
public void updatePlaceInRelationship(Context context, Relationship relationship, boolean isCreation)
        throws SQLException, AuthorizeException {
    Item leftItem = relationship.getLeftItem();
    List<Relationship> leftRelationships = findByItemAndRelationshipType(context, leftItem,
            relationship.getRelationshipType(), true);
    Item rightItem = relationship.getRightItem();
    List<Relationship> rightRelationships = findByItemAndRelationshipType(context, rightItem,
            relationship.getRelationshipType(), false);

    context.turnOffAuthorisationSystem();
    //If useForPlace for the leftlabel is false for the relationshipType,
    // we need to sort the relationships here based on leftplace.
    if (!virtualMetadataPopulator.isUseForPlaceTrueForRelationshipType(relationship.getRelationshipType(),
            true)) {// www.  j ava2s.  co m
        if (!leftRelationships.isEmpty()) {
            leftRelationships.sort(Comparator.comparingInt(Relationship::getLeftPlace));
            for (int i = 0; i < leftRelationships.size(); i++) {
                leftRelationships.get(i).setLeftPlace(i);
            }
            relationship.setLeftPlace(leftRelationships.size());
        } else {
            relationship.setLeftPlace(0);
        }
    } else {
        updateItem(context, leftItem);

    }

    //If useForPlace for the rightLabel is false for the relationshipType,
    // we need to sort the relationships here based on the rightplace.
    if (!virtualMetadataPopulator.isUseForPlaceTrueForRelationshipType(relationship.getRelationshipType(),
            false)) {
        if (!rightRelationships.isEmpty()) {
            rightRelationships.sort(Comparator.comparingInt(Relationship::getRightPlace));
            for (int i = 0; i < rightRelationships.size(); i++) {
                rightRelationships.get(i).setRightPlace(i);
            }
            relationship.setRightPlace(rightRelationships.size());
        } else {
            relationship.setRightPlace(0);
        }

    } else {
        updateItem(context, rightItem);

    }

    if (isCreation) {
        handleCreationPlaces(context, relationship);
    }
    context.restoreAuthSystemState();

}

From source file:org.gradoop.flink.model.impl.operators.matching.single.cypher.planning.queryplan.unary.ProjectEmbeddingsNode.java

@Override
protected EmbeddingMetaData computeEmbeddingMetaData() {
    final EmbeddingMetaData childMetaData = getChildNode().getEmbeddingMetaData();

    projectionKeys.sort(//  w ww .j av  a 2 s . c o  m
            Comparator.comparingInt(key -> childMetaData.getPropertyColumn(key.getLeft(), key.getRight())));

    EmbeddingMetaData embeddingMetaData = new EmbeddingMetaData();

    childMetaData.getVariables().forEach(var -> embeddingMetaData.setEntryColumn(var,
            childMetaData.getEntryType(var), childMetaData.getEntryColumn(var)));

    IntStream.range(0, projectionKeys.size()).forEach(i -> embeddingMetaData
            .setPropertyColumn(projectionKeys.get(i).getLeft(), projectionKeys.get(i).getRight(), i));

    return embeddingMetaData;
}

From source file:org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData.java

/**
 * Returns a list of all variable that are contained in the embedding.
 * The order of the variables is determined by their position within the embedding.
 *
 * @return a list of all variables//from w  ww  .  ja v  a  2  s. c  o  m
 */
public List<String> getVariables() {
    return entryMapping.entrySet().stream().sorted(Comparator.comparingInt(Map.Entry::getValue))
            .map(entry -> entry.getKey().getLeft()).collect(Collectors.toList());
}

From source file:org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData.java

/**
 * Returns a list of all property keys that are contained in the embedding regarding the
 * specified variable./*from   ww  w  . j ava2s.co m*/
 * The order of the keys is determined by the position of the property value in the embedding.
 *
 * @param variable variable name
 * @return a list of all property keys contained in the embedding
 */
public List<String> getPropertyKeys(String variable) {
    return propertyMapping.entrySet().stream().filter(entry -> entry.getKey().getLeft().equals(variable))
            .sorted(Comparator.comparingInt(Map.Entry::getValue)).map(entry -> entry.getKey().getRight())
            .collect(Collectors.toList());
}