Example usage for java.util Comparator compare

List of usage examples for java.util Comparator compare

Introduction

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

Prototype

int compare(T o1, T o2);

Source Link

Document

Compares its two arguments for order.

Usage

From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSParentQueue.java

@Override
public RMContainer preemptContainer() {
    RMContainer toBePreempted = null;//from w  ww  .j a  va 2  s .  com

    // Find the childQueue which is most over fair share
    FSQueue candidateQueue = null;
    Comparator<Schedulable> comparator = policy.getComparator();

    readLock.lock();
    try {
        for (FSQueue queue : childQueues) {
            // Skip selection for non-preemptable queue
            if (!queue.canBePreempted()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("skipping from queue=" + getName()
                            + " because it's a non-preemptable queue or there is no"
                            + " sub-queues whose resource usage exceeds fair share.");
                }
                continue;
            }

            if (candidateQueue == null || comparator.compare(queue, candidateQueue) > 0) {
                candidateQueue = queue;
            }
        }
    } finally {
        readLock.unlock();
    }

    // Let the selected queue choose which of its container to preempt
    if (candidateQueue != null) {
        toBePreempted = candidateQueue.preemptContainer();
    }
    return toBePreempted;
}

From source file:com.projity.grouping.core.hierarchy.MutableNodeHierarchy.java

private Node search(Node node, Object key, Comparator c) {
    if (c.compare((node == null) ? root : node, key) == 0)
        return node;
    Collection children = getChildren(node);
    if (children == null)
        return null;
    Iterator i = children.iterator();
    while (i.hasNext()) {
        Node found = search((Node) i.next(), key, c);
        if (found != null)
            return found;
    }/*from ww w  . ja v a2  s  . c o  m*/
    return null;
}

From source file:org.optaplanner.benchmark.impl.result.PlannerBenchmarkResult.java

private List<List<SolverBenchmarkResult>> createSameRankingListList(BenchmarkReport benchmarkReport,
        List<SolverBenchmarkResult> rankableSolverBenchmarkResultList) {
    List<List<SolverBenchmarkResult>> sameRankingListList = new ArrayList<List<SolverBenchmarkResult>>(
            rankableSolverBenchmarkResultList.size());
    if (benchmarkReport.getSolverRankingComparator() != null) {
        Comparator<SolverBenchmarkResult> comparator = Collections
                .reverseOrder(benchmarkReport.getSolverRankingComparator());
        Collections.sort(rankableSolverBenchmarkResultList, comparator);
        List<SolverBenchmarkResult> sameRankingList = null;
        SolverBenchmarkResult previousSolverBenchmarkResult = null;
        for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) {
            if (previousSolverBenchmarkResult == null
                    || comparator.compare(previousSolverBenchmarkResult, solverBenchmarkResult) != 0) {
                // New rank
                sameRankingList = new ArrayList<SolverBenchmarkResult>();
                sameRankingListList.add(sameRankingList);
            }/* w  w  w. j  a va  2 s  .  c o m*/
            sameRankingList.add(solverBenchmarkResult);
            previousSolverBenchmarkResult = solverBenchmarkResult;
        }
    } else if (benchmarkReport.getSolverRankingWeightFactory() != null) {
        SortedMap<Comparable, List<SolverBenchmarkResult>> rankedMap = new TreeMap<Comparable, List<SolverBenchmarkResult>>(
                Collections.reverseOrder());
        for (SolverBenchmarkResult solverBenchmarkResult : rankableSolverBenchmarkResultList) {
            Comparable rankingWeight = benchmarkReport.getSolverRankingWeightFactory()
                    .createRankingWeight(rankableSolverBenchmarkResultList, solverBenchmarkResult);
            List<SolverBenchmarkResult> sameRankingList = rankedMap.get(rankingWeight);
            if (sameRankingList == null) {
                sameRankingList = new ArrayList<SolverBenchmarkResult>();
                rankedMap.put(rankingWeight, sameRankingList);
            }
            sameRankingList.add(solverBenchmarkResult);
        }
        for (Map.Entry<Comparable, List<SolverBenchmarkResult>> entry : rankedMap.entrySet()) {
            sameRankingListList.add(entry.getValue());
        }
    } else {
        throw new IllegalStateException("Ranking is impossible"
                + " because solverRankingComparator and solverRankingWeightFactory are null.");
    }
    return sameRankingListList;
}

From source file:com.github.gerbsen.math.Frequency.java

/**
 * Returns the cumulative frequency of values less than or equal to v.
 * <p>/*from w  w  w  .j  a  va  2  s  .co  m*/
 * Returns 0 if v is not comparable to the values set.</p>
 *
 * @param v the value to lookup.
 * @return the proportion of values equal to v
 */
public long getCumFreq(Comparable<?> v) {
    if (getSumFreq() == 0) {
        return 0;
    }
    if (v instanceof Integer) {
        return getCumFreq(((Integer) v).longValue());
    }
    @SuppressWarnings("unchecked") // OK, freqTable is Comparable<?>
    Comparator<Comparable<?>> c = (Comparator<Comparable<?>>) freqTable.comparator();
    if (c == null) {
        c = new NaturalComparator();
    }
    long result = 0;

    try {
        Long value = freqTable.get(v);
        if (value != null) {
            result = value.longValue();
        }
    } catch (ClassCastException ex) {
        return result; // v is not comparable
    }

    if (c.compare(v, freqTable.firstKey()) < 0) {
        return 0; // v is comparable, but less than first value
    }

    if (c.compare(v, freqTable.lastKey()) >= 0) {
        return getSumFreq(); // v is comparable, but greater than the last value
    }

    Iterator<Comparable<?>> values = valuesIterator();
    while (values.hasNext()) {
        Comparable<?> nextValue = values.next();
        if (c.compare(v, nextValue) > 0) {
            result += getCount(nextValue);
        } else {
            return result;
        }
    }
    return result;
}

From source file:io.druid.query.aggregation.hyperloglog.HyperLogLogCollectorTest.java

@Test
public void testCompare1() throws Exception {
    HyperLogLogCollector collector1 = HyperLogLogCollector.makeLatestCollector();
    HyperLogLogCollector collector2 = HyperLogLogCollector.makeLatestCollector();
    collector1.add(fn.hashLong(0).asBytes());
    HyperUniquesAggregatorFactory factory = new HyperUniquesAggregatorFactory("foo", "bar");
    Comparator comparator = factory.getComparator();
    for (int i = 1; i < 100; i = i + 2) {
        collector1.add(fn.hashLong(i).asBytes());
        collector2.add(fn.hashLong(i + 1).asBytes());
        Assert.assertEquals(1, comparator.compare(collector1, collector2));
        Assert.assertEquals(1,//  w  w w.  j ava 2s . c  o  m
                Double.compare(collector1.estimateCardinality(), collector2.estimateCardinality()));
    }
}

From source file:com.xtructure.xevolution.genetics.impl.AbstractPopulation.java

@SuppressWarnings("unchecked")
@Override//w w  w .j av  a 2s .  c  o m
public void refreshStats() {
    getLogger().trace("begin %s.refreshStats()", getClass().getSimpleName());
    if (isEmpty()) {
        return;
    }
    // calculate averages
    List<Genome<D>> genomes = new ArrayList<Genome<D>>(this);
    ValueMap accMap = new ValueMap();
    for (Genome<D> genome : genomes) {
        ValueMap measures = genome.getAttributes();
        for (@SuppressWarnings("rawtypes")
        XValId id : measures.keySet()) {
            updateAccMap(id, accMap, genome);
        }
    }
    averageAttributes.clear();
    for (@SuppressWarnings("rawtypes")
    XValId valueId : accMap.keySet()) {
        if (Number.class.isAssignableFrom(valueId.getType())) {
            double average = ((Number) accMap.get(valueId)).doubleValue() / size();
            averageAttributes.put(valueId, average);
        }
    }
    // get low/high genomes by measure
    highestGenomes.clear();
    lowestGenomes.clear();
    for (XValId<?> valueId : averageAttributes.keySet()) {
        @SuppressWarnings({ "rawtypes" })
        Comparator<Genome<?>> byMeasure = new GeneticsObject.ByAttribute(valueId, true);
        Collections.sort(genomes, byMeasure);
        Genome<D> genome = genomes.get(0);
        if (highestEverGenomes.get(valueId) == null
                || byMeasure.compare(genome, highestEverGenomes.get(valueId)) < 0) {
            highestEverGenomes.put(valueId, genome);
            if (Genome.FITNESS_ATTRIBUTE_ID.equals(valueId)) {
                setAttribute(AGE_LI_ATTRIBUTE_ID, getAge());
            }
        }
        highestGenomes.put(valueId, genome);
        genome = genomes.get(genomes.size() - 1);
        if (lowestEverGenomes.get(valueId) == null
                || byMeasure.compare(genome, lowestEverGenomes.get(valueId)) > 0) {
            lowestEverGenomes.put(valueId, genome);
        }
        lowestGenomes.put(valueId, genome);
    }
    getLogger().trace("end %s.refreshStats()", getClass().getSimpleName());
}

From source file:org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler.java

protected void handleMessageInternal(Message<?> message, String lookupDestination) {
    List<Match> matches = new ArrayList<>();

    List<T> mappingsByUrl = this.destinationLookup.get(lookupDestination);
    if (mappingsByUrl != null) {
        addMatchesToCollection(mappingsByUrl, message, matches);
    }/*from   ww  w  .j  a  va  2 s  .com*/
    if (matches.isEmpty()) {
        // No direct hits, go through all mappings
        Set<T> allMappings = this.handlerMethods.keySet();
        addMatchesToCollection(allMappings, message, matches);
    }
    if (matches.isEmpty()) {
        handleNoMatch(this.handlerMethods.keySet(), lookupDestination, message);
        return;
    }
    Comparator<Match> comparator = new MatchComparator(getMappingComparator(message));
    Collections.sort(matches, comparator);

    if (logger.isTraceEnabled()) {
        logger.trace("Found " + matches.size() + " handler methods: " + matches);
    }

    Match bestMatch = matches.get(0);
    if (matches.size() > 1) {
        Match secondBestMatch = matches.get(1);
        if (comparator.compare(bestMatch, secondBestMatch) == 0) {
            Method m1 = bestMatch.handlerMethod.getMethod();
            Method m2 = secondBestMatch.handlerMethod.getMethod();
            throw new IllegalStateException("Ambiguous handler methods mapped for destination '"
                    + lookupDestination + "': {" + m1 + ", " + m2 + "}");
        }
    }

    handleMatch(bestMatch.mapping, bestMatch.handlerMethod, lookupDestination, message);
}

From source file:org.charvolant.argushiigi.server.ReferenceQueryResource.java

/**
 * Get a list of matching resources as a JSON document.
 *
 * @see org.restlet.resource.ServerResource#get()
 *///  w w w.  ja va2  s  .  co  m
@Get
public Representation get() {
    String resource = Reference.decode(this.getQueryValue(this.PARAM_RESOURCE));

    try {
        JSONObject wrap = new JSONObject();
        JSONArray result = new JSONArray();
        StmtIterator si = this.model.listStatements(null, null, this.model.createResource(resource));
        Comparator<Resource> classComparator = this.sorter.getClassComparator();

        while (si.hasNext()) {
            Statement s = si.next();
            Resource res = s.getSubject();

            if (res.isURIResource()) {
                JSONObject obj = new JSONObject();
                Reference ref = this.application.getLocalRef(new Reference(res.getURI()));
                StmtIterator ci = this.model.listStatements(res, RDF.type, (Resource) null);
                Resource cls = null;

                obj.put("name", this.sorter.getName(s.getSubject(), Locale.ENGLISH));
                obj.put("uri", s.getSubject().getURI());
                obj.put("href", ref);
                while (ci.hasNext()) {
                    Resource c = ci.next().getResource();

                    if (c.isAnon())
                        continue;
                    if (cls == null || classComparator.compare(cls, c) > 0)
                        cls = c;
                }
                if (cls == null)
                    cls = OWL.Thing;
                ref = this.application.getLocalRef(new Reference(cls.getURI()));
                obj.put("cls", this.sorter.getName(cls, Locale.ENGLISH));
                obj.put("clsUri", cls.getURI());
                obj.put("clsHref", ref);
                result.put(obj);
            }
        }
        wrap.put("aaData", result);
        return new JsonRepresentation(wrap);
    } catch (Exception ex) {
        this.application.getLogger().log(Level.SEVERE, "Unable to get references to " + resource, ex);
        this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, ex);
        return new StringRepresentation(ex.getMessage());
    }
}

From source file:org.charvolant.argushiigi.server.TypeQueryResource.java

/**
 * Get a list of matching resources as a JSON document.
 *
 * @see org.restlet.resource.ServerResource#get()
 *//*from w w  w  .jav a  2 s  .c  o  m*/
@Get
public Representation get() {
    String type = Reference.decode(this.getQueryValue(this.PARAM_TYPE));

    try {
        JSONObject wrap = new JSONObject();
        JSONArray result = new JSONArray();
        StmtIterator si = this.model.listStatements(null, RDF.type, this.model.createResource(type));
        Comparator<Resource> classComparator = this.sorter.getClassComparator();

        while (si.hasNext()) {
            Statement s = si.next();
            Resource res = s.getSubject();

            if (res.isURIResource()) {
                JSONObject obj = new JSONObject();
                Reference ref = this.application.getLocalRef(new Reference(res.getURI()));
                StmtIterator ci = this.model.listStatements(res, RDF.type, (Resource) null);
                Resource cls = null;

                obj.put("name", this.sorter.getName(s.getSubject(), Locale.ENGLISH));
                obj.put("uri", s.getSubject().getURI());
                obj.put("href", ref);
                while (ci.hasNext()) {
                    Resource c = ci.next().getResource();

                    if (c.isAnon())
                        continue;
                    if (cls == null || classComparator.compare(cls, c) > 0)
                        cls = c;
                }
                if (cls == null)
                    cls = OWL.Thing;
                ref = this.application.getLocalRef(new Reference(cls.getURI()));
                obj.put("cls", this.sorter.getName(cls, Locale.ENGLISH));
                obj.put("clsUri", cls.getURI());
                obj.put("clsHref", ref);
                result.put(obj);
            }
        }
        wrap.put("aaData", result);
        return new JsonRepresentation(wrap);
    } catch (Exception ex) {
        this.application.getLogger().log(Level.SEVERE, "Unable to get resources of type " + type, ex);
        this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL, ex);
        return new StringRepresentation(ex.getMessage());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.DatareportsServiceImpl.java

@Cached
public Map<String, Comparator> getComparatorMap(final Class clazz, final Map<String, String> colMap) {
    final Map<String, Comparator> compMap = new HashMap<String, Comparator>();
    final Comparator alphaNum = new AlphanumComparator();
    for (final Map.Entry<String, String> entry : colMap.entrySet()) {
        compMap.put(entry.getKey(), new Comparator() {
            public int compare(final Object o1, final Object o2) {
                try {
                    final Method getter = GetterMethod.getGetter(clazz, entry.getKey());
                    final Object obj1 = getter.invoke(clazz.cast(o1));
                    final Object obj2 = getter.invoke(clazz.cast(o2));
                    final String str1 = obj1 == null ? "" : obj1.toString();
                    final String str2 = obj2 == null ? "" : obj2.toString();
                    if (str1 == null || str2 == null) {
                        return 0;
                    }//from  w w w.  j  a va  2  s  .  com
                    return alphaNum.compare(str1.toUpperCase(), str2.toUpperCase());
                } catch (Exception e) {
                    logger.debug(FancyExceptionLogger.printException(e));
                    return 0;
                }
            }
        });
    }
    return compMap;
}