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.kalypso.chart.ext.observation.deprecated.BranchLayer.java

/**
 * @see de.openali.odysseus.chart.framework.model.layer.ITooltipChartLayer#getHover(org.eclipse.swt.graphics.Point)
 *///  w w w  .j  ava 2 s  .c o  m
@Override
@SuppressWarnings({ "unchecked", "deprecation" })
public EditInfo getHover(final Point pos) {
    // Umrechnen von screen nach logisch
    final int tolerance = 4;
    final IAxis domainAxis = getDomainAxis();
    final IAxis targetAxis = getTargetAxis();

    int domPos;
    int tarPos;
    if (domainAxis.getPosition().getOrientation().equals(ORIENTATION.HORIZONTAL)) {
        domPos = pos.x;
        tarPos = pos.y;
    } else {
        domPos = pos.y;
        tarPos = pos.x;
    }

    final Number domainVal1 = domainAxis.screenToNumeric(domPos - tolerance);
    final Number domainVal2 = domainAxis.screenToNumeric(domPos + tolerance);
    final Number targetVal1 = targetAxis.screenToNumeric(tarPos + tolerance);
    final Number targetVal2 = targetAxis.screenToNumeric(tarPos - tolerance);

    final Comparator ct = getTargetAxis().getDataOperator(domainVal1.getClass()).getComparator();
    final Comparator cd = getDomainAxis().getDataOperator(targetVal1.getClass()).getComparator();

    // Jetzt rausfinden, welches der grere und welcher der kleinere Wert ist und entsprechend zuweisen
    Object domainValMin;
    Object domainValMax;
    Object targetValMin;
    Object targetValMax;
    if (cd.compare(domainVal1, domainVal2) <= 0) {
        domainValMin = domainVal1;
        domainValMax = domainVal2;
    } else {
        domainValMin = domainVal2;
        domainValMax = domainVal1;
    }

    if (ct.compare(targetVal1, targetVal2) <= 0) {
        targetValMin = targetVal1;
        targetValMax = targetVal2;
    } else {
        targetValMin = targetVal2;
        targetValMax = targetVal1;
    }

    // herausfinden, ob der Punkt IN DER NAEHE eines Datenpunktes liegt
    for (int i = 0; i < m_data.size(); i++) {
        final IRecord record = m_data.get(i);
        final Object domainVal = record.getValue(m_domainComponent);
        // Abbrechen, wenn wir ber die Domain-Range raus sind
        if (cd.compare(domainVal, domainValMax) > 0)
            break;

        if (cd.compare(domainVal, domainValMin) >= 0) {
            final Object targetVal = record.getValue(m_targetComponent);
            if (ct.compare(targetVal, targetValMin) >= 0 && ct.compare(targetVal, targetValMax) <= 0)
                return createTooltipInfo(pos, i);
        }
    }

    return null;

}

From source file:org.ambraproject.admin.action.AdminTopActionTest.java

@Test(dependsOnMethods = "testBasicRequest", dataProvider = "articlesToSort", alwaysRun = true)
public void testSort(String directive, Comparator<ArticleInfo> comparator) {
    action.setAction(directive);//from ww  w .  j  ava 2 s. c  om
    action.processArticles();

    assertTrue(action.getPublishableArticles().size() > 1, "action didn't have any publishable articles");

    for (int i = 0; i < action.getPublishableArticles().size() - 1; i++) {
        ArticleInfo article = action.getPublishableArticles().get(i);
        ArticleInfo nextArticle = action.getPublishableArticles().get(i + 1);
        assertTrue(comparator.compare(article, nextArticle) <= 0,
                "Articles weren't in order when sorting by: '" + directive + "'");
    }
}

From source file:org.optaplanner.benchmark.impl.DefaultPlannerBenchmark.java

private List<List<SolverBenchmark>> createSameRankingListList(
        List<SolverBenchmark> rankableSolverBenchmarkList) {
    List<List<SolverBenchmark>> sameRankingListList = new ArrayList<List<SolverBenchmark>>(
            rankableSolverBenchmarkList.size());
    if (solverBenchmarkRankingComparator != null) {
        Comparator<SolverBenchmark> comparator = Collections.reverseOrder(solverBenchmarkRankingComparator);
        Collections.sort(rankableSolverBenchmarkList, comparator);
        List<SolverBenchmark> sameRankingList = null;
        SolverBenchmark previousSolverBenchmark = null;
        for (SolverBenchmark solverBenchmark : rankableSolverBenchmarkList) {
            if (previousSolverBenchmark == null
                    || comparator.compare(previousSolverBenchmark, solverBenchmark) != 0) {
                // New rank
                sameRankingList = new ArrayList<SolverBenchmark>();
                sameRankingListList.add(sameRankingList);
            }//from   w  ww.  j a  va  2 s  .c  om
            sameRankingList.add(solverBenchmark);
            previousSolverBenchmark = solverBenchmark;
        }
    } else if (solverBenchmarkRankingWeightFactory != null) {
        SortedMap<Comparable, List<SolverBenchmark>> rankedMap = new TreeMap<Comparable, List<SolverBenchmark>>(
                new ReverseComparator());
        for (SolverBenchmark solverBenchmark : rankableSolverBenchmarkList) {
            Comparable rankingWeight = solverBenchmarkRankingWeightFactory
                    .createRankingWeight(rankableSolverBenchmarkList, solverBenchmark);
            List<SolverBenchmark> sameRankingList = rankedMap.get(rankingWeight);
            if (sameRankingList == null) {
                sameRankingList = new ArrayList<SolverBenchmark>();
                rankedMap.put(rankingWeight, sameRankingList);
            }
            sameRankingList.add(solverBenchmark);
        }
        for (Map.Entry<Comparable, List<SolverBenchmark>> entry : rankedMap.entrySet()) {
            sameRankingListList.add(entry.getValue());
        }
    } else {
        throw new IllegalStateException("Ranking is impossible"
                + " because solverBenchmarkRankingComparator and solverBenchmarkRankingWeightFactory are null.");
    }
    return sameRankingListList;
}

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

private void determineRanking(List<SingleBenchmarkResult> rankedSingleBenchmarkResultList) {
    Comparator singleBenchmarkRankingComparator = new SingleBenchmarkRankingComparator();
    Collections.sort(rankedSingleBenchmarkResultList,
            Collections.reverseOrder(singleBenchmarkRankingComparator));
    int ranking = 0;
    SingleBenchmarkResult previousSingleBenchmarkResult = null;
    int previousSameRankingCount = 0;
    for (SingleBenchmarkResult singleBenchmarkResult : rankedSingleBenchmarkResultList) {
        if (previousSingleBenchmarkResult != null && singleBenchmarkRankingComparator
                .compare(previousSingleBenchmarkResult, singleBenchmarkResult) != 0) {
            ranking += previousSameRankingCount;
            previousSameRankingCount = 0;
        }//w w  w .ja va2  s.c  o  m
        singleBenchmarkResult.setRanking(ranking);
        previousSingleBenchmarkResult = singleBenchmarkResult;
        previousSameRankingCount++;
    }
    winningSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null
            : rankedSingleBenchmarkResultList.get(0);
    worstSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null
            : rankedSingleBenchmarkResultList.get(rankedSingleBenchmarkResultList.size() - 1);
}

From source file:org.alfresco.repo.virtual.page.PageCollator.java

private boolean collate(List<R> objects, List<R> pageObjects, int pageSkip, int pageSize,
        Comparator<R> comparator, List<R> collatedResult) {

    final int resultsSize = objects.size();
    final int inPageSize = pageObjects.size();
    if (pageSkip >= resultsSize + inPageSize) {
        return true;
    }//from  w ww. j  a v a  2  s.  c  o  m

    List<R> collation = new ArrayList<>(objects.size() + pageObjects.size());
    collation.addAll(pageObjects);

    for (int i = 0; i < resultsSize; i++) {
        final int collationSize = collation.size();
        final R result = objects.get(i);
        int j = 0;

        if (comparator != null) {
            for (; j < collationSize; j++) {
                final R collated = collation.get(j);
                if (comparator.compare(result, collated) <= 0) {
                    break;
                }
            }
        }

        collation.add(j, result);
    }

    final R[] collationArray = (R[]) collation.toArray();
    final int zeroPageSize = (pageSize == 0 ? collationArray.length - pageSkip : pageSize);
    final int to = Math.min(pageSkip + zeroPageSize, collationArray.length);

    collatedResult.addAll(Arrays.asList(Arrays.copyOfRange(collationArray, pageSkip, to)));

    return to == collationArray.length;
}

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

@Nullable
private Match<T> getHandlerMethod(Message<?> message) {
    List<Match<T>> matches = new ArrayList<>();

    RouteMatcher.Route destination = getDestination(message);
    List<T> mappingsByUrl = destination != null ? this.destinationLookup.get(destination.value()) : null;
    if (mappingsByUrl != null) {
        addMatchesToCollection(mappingsByUrl, message, matches);
    }//from w  w  w .  j  a  va2  s. c o  m
    if (matches.isEmpty()) {
        // No direct hits, go through all mappings
        Set<T> allMappings = this.handlerMethods.keySet();
        addMatchesToCollection(allMappings, message, matches);
    }
    if (matches.isEmpty()) {
        handleNoMatch(destination, message);
        return null;
    }
    Comparator<Match<T>> comparator = new MatchComparator(getMappingComparator(message));
    matches.sort(comparator);
    if (logger.isTraceEnabled()) {
        logger.trace("Found " + matches.size() + " handler methods: " + matches);
    }
    Match<T> bestMatch = matches.get(0);
    if (matches.size() > 1) {
        Match<T> secondBestMatch = matches.get(1);
        if (comparator.compare(bestMatch, secondBestMatch) == 0) {
            HandlerMethod m1 = bestMatch.handlerMethod;
            HandlerMethod m2 = secondBestMatch.handlerMethod;
            throw new IllegalStateException(
                    "Ambiguous handler methods mapped for destination '" + destination.value() + "': {"
                            + m1.getShortLogMessage() + ", " + m2.getShortLogMessage() + "}");
        }
    }
    return bestMatch;
}

From source file:ca.sqlpower.sqlobject.TestSQLColumn.java

public void testCompareTo() throws Exception {
    SQLColumn cowCol = table1pk.getColumnByName("cow");
    SQLColumn mooCol = table1pk.getColumnByName("moo");
    SQLColumn fooCol = table1pk.getColumnByName("foo");

    // check column name comparator
    Comparator<SQLColumn> nameComp = new SQLColumn.ColumnNameComparator();
    assertTrue(nameComp.compare(cowCol, mooCol) < 0);
    assertTrue(nameComp.compare(mooCol, fooCol) > 0);
    assertTrue(nameComp.compare(fooCol, cowCol) > 0);
    assertTrue(nameComp.compare(cowCol, fooCol) < 0);
    assertTrue(nameComp.compare(cowCol, cowCol) == 0);
    cowCol.setName(mooCol.getName());//from   w ww  .j  a v a 2s  . c om
    assertTrue(nameComp.compare(cowCol, mooCol) == 0);
}

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

private void determineRanking(List<SubSingleBenchmarkResult> rankedSubSingleBenchmarkResultList) {
    Comparator subSingleBenchmarkRankingComparator = new SubSingleBenchmarkRankingComparator();
    Collections.sort(rankedSubSingleBenchmarkResultList,
            Collections.reverseOrder(subSingleBenchmarkRankingComparator));
    int ranking = 0;
    SubSingleBenchmarkResult previousSubSingleBenchmarkResult = null;
    int previousSameRankingCount = 0;
    for (SubSingleBenchmarkResult subSingleBenchmarkResult : rankedSubSingleBenchmarkResultList) {
        if (previousSubSingleBenchmarkResult != null && subSingleBenchmarkRankingComparator
                .compare(previousSubSingleBenchmarkResult, subSingleBenchmarkResult) != 0) {
            ranking += previousSameRankingCount;
            previousSameRankingCount = 0;
        }/* ww  w  .j  a v  a2 s  .  c o m*/
        subSingleBenchmarkResult.setRanking(ranking);
        previousSubSingleBenchmarkResult = subSingleBenchmarkResult;
        previousSameRankingCount++;
    }
}

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

protected void handleMessageInternal(Message<?> message, String lookupDestination) {

    List<Match> matches = new ArrayList<Match>();

    List<T> mappingsByUrl = this.destinationLookup.get(lookupDestination);
    if (mappingsByUrl != null) {
        addMatchesToCollection(mappingsByUrl, message, matches);
    }/*www  .  ja v a  2s  .  c o  m*/

    if (matches.isEmpty()) {
        // No direct hits, go through all mappings
        Set<T> allMappings = this.handlerMethods.keySet();
        addMatchesToCollection(allMappings, message, matches);
    }

    if (matches.isEmpty()) {
        handleNoMatch(handlerMethods.keySet(), lookupDestination, message);
        return;
    }

    Comparator<Match> comparator = new MatchComparator(getMappingComparator(message));
    Collections.sort(matches, comparator);

    if (logger.isTraceEnabled()) {
        logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupDestination + "] : "
                + 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:name.nanek.gdwprototype.shared.model.support.CompareToBuilder.java

/**
 * <p>Appends to the <code>builder</code> the comparison of
 * two <code>Object</code>s.</p>
 *
 * <ol>//from  w  ww  . j  a v a  2 s .co m
 * <li>Check if <code>lhs == rhs</code></li>
 * <li>Check if either <code>lhs</code> or <code>rhs</code> is <code>null</code>,
 *     a <code>null</code> object is less than a non-<code>null</code> object</li>
 * <li>Check the object contents</li>
 * </ol>
 *
 * <p>If <code>lhs</code> is an array, array comparison methods will be used.
 * Otherwise <code>comparator</code> will be used to compare the objects.
 * If <code>comparator</code> is <code>null</code>, <code>lhs</code> must
 * implement {@link Comparable} instead.</p>
 *
 * @param lhs  left-hand object
 * @param rhs  right-hand object
 * @param comparator  <code>Comparator</code> used to compare the objects,
 *  <code>null</code> means treat lhs as <code>Comparable</code>
 * @return this - used to chain append calls
 * @throws ClassCastException  if <code>rhs</code> is not assignment-compatible
 *  with <code>lhs</code>
 * @since 2.0
 */
public CompareToBuilder append(Object lhs, Object rhs, Comparator<?> comparator) {
    if (comparison != 0) {
        return this;
    }
    if (lhs == rhs) {
        return this;
    }
    if (lhs == null) {
        comparison = -1;
        return this;
    }
    if (rhs == null) {
        comparison = +1;
        return this;
    }
    if (lhs.getClass().isArray()) {
        // switch on type of array, to dispatch to the correct handler
        // handles multi dimensional arrays
        // throws a ClassCastException if rhs is not the correct array type
        if (lhs instanceof long[]) {
            append((long[]) lhs, (long[]) rhs);
        } else if (lhs instanceof int[]) {
            append((int[]) lhs, (int[]) rhs);
        } else if (lhs instanceof short[]) {
            append((short[]) lhs, (short[]) rhs);
        } else if (lhs instanceof char[]) {
            append((char[]) lhs, (char[]) rhs);
        } else if (lhs instanceof byte[]) {
            append((byte[]) lhs, (byte[]) rhs);
        } else if (lhs instanceof double[]) {
            append((double[]) lhs, (double[]) rhs);
        } else if (lhs instanceof float[]) {
            append((float[]) lhs, (float[]) rhs);
        } else if (lhs instanceof boolean[]) {
            append((boolean[]) lhs, (boolean[]) rhs);
        } else {
            // not an array of primitives
            // throws a ClassCastException if rhs is not an array
            append((Object[]) lhs, (Object[]) rhs, comparator);
        }
    } else {
        // the simple case, not an array, just test the element
        if (comparator == null) {
            @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
            final Comparable<Object> comparable = (Comparable<Object>) lhs;
            comparison = comparable.compareTo(rhs);
        } else {
            @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
            final Comparator<Object> comparator2 = (Comparator<Object>) comparator;
            comparison = comparator2.compare(lhs, rhs);
        }
    }
    return this;
}