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.hdfs.server.namenode.TestRedundantEditLogInputStream.java

@Test
public void testStreamComparator() throws Exception {
    Comparator<EditLogInputStream> comparator = RedundantEditLogInputStream.segmentComparator;

    EditLogInputStream elis1 = new EditLogFileInputStream(new File("/foo/bar"), 0, 10, true);
    EditLogInputStream elis2 = new EditLogFileInputStream(new File("/foo/bar"), 0, 11, true);

    EditLogInputStream elis3 = new EditLogFileInputStream(new File("/foo/bar"), 0, 10, false);
    EditLogInputStream elis4 = new EditLogFileInputStream(new File("/foo/bar"), 0, 11, false);

    // finalized is always preferred
    assertTrue(0 > comparator.compare(elis1, elis3));
    assertTrue(0 < comparator.compare(elis3, elis1));

    assertTrue(0 > comparator.compare(elis2, elis3));
    assertTrue(0 < comparator.compare(elis3, elis2));

    // finalized longer is preferred
    assertTrue(0 < comparator.compare(elis3, elis4));
    assertTrue(0 > comparator.compare(elis4, elis3));

    // inprogress longer is preferred
    assertTrue(0 < comparator.compare(elis1, elis2));
    assertTrue(0 > comparator.compare(elis2, elis1));
}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial1.Algorithm.java

private void setTopItemSimilarity(Map<Integer, Queue<IndexAndScore>> topItemSimilarity, Integer itemID1,
        Integer index2, double score, int capacity, Comparator<IndexAndScore> comparator) {
    Queue<IndexAndScore> queue = topItemSimilarity.get(itemID1);
    if (queue == null) {
        queue = new PriorityQueue<IndexAndScore>(capacity, comparator);
        topItemSimilarity.put(itemID1, queue);
    }/* ww w  .  j  av a  2s.com*/
    IndexAndScore entry = new IndexAndScore(index2, score);
    if (queue.size() < capacity)
        queue.add(entry);
    else if (comparator.compare(queue.peek(), entry) < 0) {
        queue.poll();
        queue.add(entry);
    }
}

From source file:org.ascent.mmkp.FMRedux.java

public List<FeatureSelection> sortedMerge(List<FeatureSelection> trg, List<FeatureSelection> mergin,
        Comparator<FeatureSelection> comp) {
    ArrayList<FeatureSelection> merged = new ArrayList<FeatureSelection>(trg.size() + mergin.size());
    int i = 0;//from  ww w.  ja v a  2  s. co m
    int j = 0;
    while (i < trg.size() && j < mergin.size()) {
        int v = comp.compare(trg.get(i), mergin.get(j));
        if (v == i) {
            merged.add(trg.get(i));
            merged.add(mergin.get(j));
            i++;
            j++;
        } else if (v < 0) {
            merged.add(trg.get(i));
            i++;
        } else {
            merged.add(mergin.get(j));
            j++;
        }
    }
    for (int k = i; k < trg.size(); k++) {
        merged.add(trg.get(k));
    }
    for (int k = j; k < mergin.size(); k++) {
        merged.add(mergin.get(k));
    }

    return merged;
}

From source file:ca.mymenuapp.ui.activities.MainActivity.java

private void sortRestaurants(final Comparator<Restaurant> restaurantComparator) {
    Observable.from(restaurants).toSortedList(new Func2<Restaurant, Restaurant, Integer>() {
        @Override//from   www.ja  v a 2s .com
        public Integer call(Restaurant lhs, Restaurant rhs) {
            return restaurantComparator.compare(lhs, rhs);
        }
    }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new EndlessObserver<List<Restaurant>>() {
                @Override
                public void onNext(List<Restaurant> restaurantList) {
                    bus.post(new OnRestaurantListAvailableEvent(restaurantList));
                }
            });
}

From source file:org.polymap.rhei.table.FeatureTableViewer.java

/**
 * Sorts the table entries by delegating the call to the content provider.
 * //from   w w w.  j  a  v  a  2  s  . com
 * @param column The table column to sort.
 * @param dir {@link SWT#UP}, {@link SWT#DOWN} or {@link SWT#NONE}
 * @param column
 */
public void sortContent(IFeatureTableColumn column, int dir) {
    IContentProvider contentProvider = getContentProvider();

    if (contentProvider == null) {
        throw new IllegalStateException("Call sortContent() after content provider is set.");
    }
    // ContentProvider
    else if (contentProvider instanceof ISortingContentProvider) {
        ((ISortingContentProvider) contentProvider).sortContent(column, dir);
    }
    // normal
    else {
        Comparator<IFeatureTableElement> comparator = column.newComparator(dir);
        setComparator(new ViewerComparator(comparator) {
            public int compare(Viewer viewer, Object e1, Object e2) {
                return comparator.compare((IFeatureTableElement) e1, (IFeatureTableElement) e2);
            }
        });
    }
    getTable().setSortColumn(column.getViewerColumn().getColumn());
    getTable().setSortDirection(dir);
}

From source file:org.artifactory.rest.resource.ci.BuildResource.java

/**
 * Get the build name and number from the request url and send back the exact build for those parameters
 *
 * @return BuildInfo json object/* w  ww. j  a v  a 2 s. co  m*/
 */
@GET
@Path("/{buildName: .+}/{buildNumber: .+}")
@Produces({ BuildRestConstants.MT_BUILD_INFO, BuildRestConstants.MT_BUILDS_DIFF, MediaType.APPLICATION_JSON })
public Response getBuildInfo(@PathParam("buildName") String buildName,
        @PathParam("buildNumber") String buildNumber, @QueryParam("started") String buildStarted,
        @QueryParam("diff") String diffNumber) throws IOException {

    if (authorizationService.isAnonUserAndAnonBuildInfoAccessDisabled()) {
        throw new AuthorizationRestException(anonAccessDisabledMsg);
    }
    if (!authorizationService.canDeployToLocalRepository()) {
        throw new AuthorizationRestException();
    }

    Build build = null;
    if (StringUtils.isNotBlank(buildStarted)) {
        BuildRun buildRun = buildService.getBuildRun(buildName, buildNumber, buildStarted);
        if (buildRun != null) {
            build = buildService.getBuild(buildRun);
        }
    } else {
        build = buildService.getLatestBuildByNameAndNumber(buildName, buildNumber);
    }

    if (build == null) {
        String msg = String.format("No build was found for build name: %s, build number: %s %s", buildName,
                buildNumber, StringUtils.isNotBlank(buildStarted) ? ", build started: " + buildStarted : "");
        throw new NotFoundException(msg);
    }

    if (queryParamsContainKey("diff")) {
        Build secondBuild = buildService.getLatestBuildByNameAndNumber(buildName, diffNumber);
        if (secondBuild == null) {
            throw new NotFoundException(String.format(
                    "No build was found for build name: %s , build number: %s ", buildName, diffNumber));
        }
        BuildRun buildRun = buildService.getBuildRun(build.getName(), build.getNumber(), build.getStarted());
        BuildRun secondBuildRun = buildService.getBuildRun(secondBuild.getName(), secondBuild.getNumber(),
                secondBuild.getStarted());
        Comparator<BuildRun> comparator = BuildRunComparators.getBuildStartDateComparator();
        if (comparator.compare(buildRun, secondBuildRun) < 0) {
            throw new BadRequestException(
                    "Build number should be greater than the build number to compare against.");
        }
        return prepareBuildDiffResponse(build, secondBuild, request);
    } else {
        return prepareGetBuildResponse(build);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.TestFSHLog.java

/**
 * tests the log comparator. Ensure that we are not mixing meta logs with non-meta logs (throws
 * exception if we do). Comparison is based on the timestamp present in the wal name.
 * @throws Exception//from www  .  j  av a 2s.  c o m
 */
@Test
public void testWALComparator() throws Exception {
    FSHLog wal1 = null;
    FSHLog walMeta = null;
    try {
        wal1 = new FSHLog(fs, FSUtils.getRootDir(conf), dir.toString(), HConstants.HREGION_OLDLOGDIR_NAME, conf,
                null, true, null, null);
        LOG.debug("Log obtained is: " + wal1);
        Comparator<Path> comp = wal1.LOG_NAME_COMPARATOR;
        Path p1 = wal1.computeFilename(11);
        Path p2 = wal1.computeFilename(12);
        // comparing with itself returns 0
        assertTrue(comp.compare(p1, p1) == 0);
        // comparing with different filenum.
        assertTrue(comp.compare(p1, p2) < 0);
        walMeta = new FSHLog(fs, FSUtils.getRootDir(conf), dir.toString(), HConstants.HREGION_OLDLOGDIR_NAME,
                conf, null, true, null, DefaultWALProvider.META_WAL_PROVIDER_ID);
        Comparator<Path> compMeta = walMeta.LOG_NAME_COMPARATOR;

        Path p1WithMeta = walMeta.computeFilename(11);
        Path p2WithMeta = walMeta.computeFilename(12);
        assertTrue(compMeta.compare(p1WithMeta, p1WithMeta) == 0);
        assertTrue(compMeta.compare(p1WithMeta, p2WithMeta) < 0);
        // mixing meta and non-meta logs gives error
        boolean ex = false;
        try {
            comp.compare(p1WithMeta, p2);
        } catch (IllegalArgumentException e) {
            ex = true;
        }
        assertTrue("Comparator doesn't complain while checking meta log files", ex);
        boolean exMeta = false;
        try {
            compMeta.compare(p1WithMeta, p2);
        } catch (IllegalArgumentException e) {
            exMeta = true;
        }
        assertTrue("Meta comparator doesn't complain while checking log files", exMeta);
    } finally {
        if (wal1 != null) {
            wal1.close();
        }
        if (walMeta != null) {
            walMeta.close();
        }
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.AbstractTestFSWAL.java

/**
 * tests the log comparator. Ensure that we are not mixing meta logs with non-meta logs (throws
 * exception if we do). Comparison is based on the timestamp present in the wal name.
 * @throws Exception//  w  ww.jav a2s  .  c  o m
 */
@Test
public void testWALComparator() throws Exception {
    AbstractFSWAL<?> wal1 = null;
    AbstractFSWAL<?> walMeta = null;
    try {
        wal1 = newWAL(FS, FSUtils.getRootDir(CONF), DIR.toString(), HConstants.HREGION_OLDLOGDIR_NAME, CONF,
                null, true, null, null);
        LOG.debug("Log obtained is: " + wal1);
        Comparator<Path> comp = wal1.LOG_NAME_COMPARATOR;
        Path p1 = wal1.computeFilename(11);
        Path p2 = wal1.computeFilename(12);
        // comparing with itself returns 0
        assertTrue(comp.compare(p1, p1) == 0);
        // comparing with different filenum.
        assertTrue(comp.compare(p1, p2) < 0);
        walMeta = newWAL(FS, FSUtils.getRootDir(CONF), DIR.toString(), HConstants.HREGION_OLDLOGDIR_NAME, CONF,
                null, true, null, AbstractFSWALProvider.META_WAL_PROVIDER_ID);
        Comparator<Path> compMeta = walMeta.LOG_NAME_COMPARATOR;

        Path p1WithMeta = walMeta.computeFilename(11);
        Path p2WithMeta = walMeta.computeFilename(12);
        assertTrue(compMeta.compare(p1WithMeta, p1WithMeta) == 0);
        assertTrue(compMeta.compare(p1WithMeta, p2WithMeta) < 0);
        // mixing meta and non-meta logs gives error
        boolean ex = false;
        try {
            comp.compare(p1WithMeta, p2);
        } catch (IllegalArgumentException e) {
            ex = true;
        }
        assertTrue("Comparator doesn't complain while checking meta log files", ex);
        boolean exMeta = false;
        try {
            compMeta.compare(p1WithMeta, p2);
        } catch (IllegalArgumentException e) {
            exMeta = true;
        }
        assertTrue("Meta comparator doesn't complain while checking log files", exMeta);
    } finally {
        if (wal1 != null) {
            wal1.close();
        }
        if (walMeta != null) {
            walMeta.close();
        }
    }
}

From source file:de.tud.kom.p2psim.impl.overlay.dht.kademlia2.setup.AbstractNodeFactory.java

/**
 * Returns all IDs that are closer to key than ref.
 * //from w ww  . j ava  2 s  . c om
 * @param ref
 *            a reference HKademliaOverlayID.
 * @param key
 *            the KademliaOverlayKey according to which the distance is
 *            calculated.
 * @return a Collection with all HKademliaOverlayIDs of peers that are
 *         closer to key than ref.
 */
public final Collection<HKademliaOverlayID> getCloserIDs(final HKademliaOverlayID ref,
        final KademliaOverlayKey key) {
    final List<HKademliaOverlayID> closer;
    final Comparator<HKademliaOverlayID> xorToKey;

    closer = new ArrayList<HKademliaOverlayID>(config.getBucketSize() * 2);
    xorToKey = new KademliaOverlayIDXORMaxComparator<HKademliaOverlayID>(key.getBigInt());

    for (final HKademliaOverlayID candidate : constructedNodes.keySet()) {
        if (xorToKey.compare(candidate, ref) < 0) {
            closer.add(candidate);
        }
    }

    return closer;
}

From source file:edu.umn.cs.spatialHadoop.core.RectangleNN.java

/**
 * Self join of rectangles. This method runs faster than the general version
 * because it just performs the filter step based on the rectangles.
 * @param output//  w w  w .j av a2 s . co  m
 * @return
 * @throws IOException
 */
public static <S1 extends Rectangle, S2 extends Rectangle> int SpatialJoin_rectangles(final S1[] R,
        final S2[] S, OutputCollector<S1, S2> output, Reporter reporter) throws IOException {
    int count = 0;

    final Comparator<Rectangle> comparator = new Comparator<Rectangle>() {
        @Override
        public int compare(Rectangle o1, Rectangle o2) {
            if (o1.x1 == o2.x1)
                return 0;
            return o1.x1 < o2.x1 ? -1 : 1;
        }
    };

    long t1 = System.currentTimeMillis();
    LOG.info("Spatial Join of " + R.length + " X " + S.length + "shapes");
    Arrays.sort(R, comparator);
    Arrays.sort(S, comparator);

    int i = 0, j = 0;

    try {
        while (i < R.length && j < S.length) {
            S1 r;
            S2 s;
            if (comparator.compare(R[i], S[j]) < 0) {
                r = R[i];
                int jj = j;

                while ((jj < S.length) && ((s = S[jj]).getMBR().x1 <= r.getMBR().x2)) {
                    if (r.isIntersected(s)) {
                        if (output != null)
                            output.collect(r, s);
                        count++;
                    }
                    jj++;
                }
                i++;
                if (reporter != null)
                    reporter.progress();
            } else {
                s = S[j];
                int ii = i;

                while ((ii < R.length) && ((r = R[ii]).getMBR().x1 <= s.getMBR().x2)) {
                    if (r.isIntersected(s)) {
                        if (output != null)
                            output.collect(r, s);
                        count++;
                    }
                    ii++;
                    if (reporter != null)
                        reporter.progress();
                }
                j++;
            }
            if (reporter != null)
                reporter.progress();
        }

    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    long t2 = System.currentTimeMillis();
    LOG.info("Finished spatial join plane sweep in " + (t2 - t1) + " millis and found " + count + " pairs");

    return count;
}