List of usage examples for java.util Comparator compare
int compare(T o1, T o2);
From source file:module.mailtracking.presentationTier.MailTrackingAction.java
private java.util.List<CorrespondenceEntry> limitAndOrderSearchedEntries(java.util.List searchedEntries, final Comparator[] propertiesToCompare, final Integer[] orderToUse, Integer iDisplayStart, Integer iDisplayLength) { Collections.sort(searchedEntries, new Comparator<CorrespondenceEntry>() { @Override/*from w w w. j a v a 2 s.c o m*/ public int compare(CorrespondenceEntry oLeft, CorrespondenceEntry oRight) { for (int i = 0; i < propertiesToCompare.length; i++) { try { Comparator comparator = propertiesToCompare[i]; if (comparator.compare(oLeft, oRight) != 0) { return orderToUse[i] * comparator.compare(oLeft, oRight); } } catch (Exception e) { throw new RuntimeException(e); } } return 0; } }); return searchedEntries.subList(iDisplayStart, Math.min(iDisplayStart + iDisplayLength, searchedEntries.size())); }
From source file:enumj.Enumerator.java
/** * Returns an enumerator enumerating over an ordered sequence between * a start and an exclusive end./* w ww . j a v a2 s . c om*/ * * @param <E> type of enumerated elements. * @param startInclusive the first element in the sequence. * @param endExclusive the exclusive sequence end. * @param succ {@link UnaryOperator} instance returning the successor of * a given element. * @param cmp {@link Comparator} instance comparing enumerated elements * @return the enumerator covering the range. * @exception IllegalArgumentException <code>succ</code> or <code>cmp</code> * is null. */ public static <E> Enumerator<E> range(E startInclusive, E endExclusive, UnaryOperator<E> succ, Comparator<? super E> cmp) { Checks.ensureNotNull(succ, Messages.NULL_ENUMERATOR_GENERATOR); Checks.ensureNotNull(cmp, Messages.NULL_ENUMERATOR_COMPARATOR); return cmp.compare(startInclusive, endExclusive) >= 0 ? Enumerator.empty() : iterate(startInclusive, succ).takeWhile(e -> cmp.compare(e, endExclusive) < 0); }
From source file:enumj.Enumerator.java
/** * Returns an enumerator enumerating over an ordered sequence between * a start and an inclusive end./*from w w w. j av a2s .co m*/ * * @param <E> type of enumerated elements. * @param startInclusive the first element in the sequence. * @param endInclusive the last element in the sequence. * @param succ {@link UnaryOperator} instance returning the successor of * a given element. * @param cmp {@link Comparator} instance comparing enumerated elements * @return the enumerator covering the range. * @exception IllegalArgumentException <code>succ</code> or <code>cmp</code> * is null. */ public static <E> Enumerator<E> rangeClosed(E startInclusive, E endInclusive, UnaryOperator<E> succ, Comparator<? super E> cmp) { Checks.ensureNotNull(succ, Messages.NULL_ENUMERATOR_GENERATOR); Checks.ensureNotNull(cmp, Messages.NULL_ENUMERATOR_COMPARATOR); return cmp.compare(startInclusive, endInclusive) > 0 ? Enumerator.empty() : iterate(startInclusive, succ).takeWhile(e -> cmp.compare(e, endInclusive) <= 0); }
From source file:org.ambraproject.admin.action.AdminTopActionTest.java
@DataProvider(name = "articlesToSort") public Object[][] getArticlesToSort() { //some fake pub dates Calendar oneYearAgo = Calendar.getInstance(); oneYearAgo.add(Calendar.YEAR, -1); Calendar oneMonthAgo = Calendar.getInstance(); oneMonthAgo.add(Calendar.MONTH, -1); Calendar today = Calendar.getInstance(); //Populate db w/ some articles Article article1 = new Article(); article1.setDoi("id:article-for-sorting1"); article1.setDate(oneYearAgo.getTime()); article1.setState(Article.STATE_UNPUBLISHED); article1.seteIssn(defaultJournal.geteIssn()); dummyDataStore.store(article1);// w w w.jav a 2 s . c om Article article2 = new Article(); article2.setDoi("id:article-for-sorting2"); article2.setDate(today.getTime()); article2.setState(Article.STATE_UNPUBLISHED); article2.seteIssn(defaultJournal.geteIssn()); dummyDataStore.store(article2); Article article3 = new Article(); article3.setDoi("id:article-for-sorting3"); article3.setDate(oneMonthAgo.getTime()); article3.setState(Article.STATE_UNPUBLISHED); article3.seteIssn(defaultJournal.geteIssn()); dummyDataStore.store(article3); final Comparator<ArticleInfo> dateAscending = new Comparator<ArticleInfo>() { @Override public int compare(ArticleInfo article, ArticleInfo article1) { if (article.getDate() == null) { return article1.getDate() == null ? 0 : -1; } else if (article1.getDate() == null) { return 1; } return article.getDate().compareTo(article1.getDate()); } }; final Comparator<ArticleInfo> dateDescending = new Comparator<ArticleInfo>() { @Override public int compare(ArticleInfo article, ArticleInfo article1) { return -1 * dateAscending.compare(article, article1); } }; final Comparator<ArticleInfo> doiAscending = new Comparator<ArticleInfo>() { @Override public int compare(ArticleInfo article, ArticleInfo article1) { return article.getDoi().compareTo(article1.getDoi()); } }; final Comparator<ArticleInfo> doiDescending = new Comparator<ArticleInfo>() { @Override public int compare(ArticleInfo article, ArticleInfo article1) { return -1 * doiAscending.compare(article, article1); } }; return new Object[][] { { "Sort by Pub Date Asc", dateAscending }, { "Sort by Pub Date Desc", dateDescending }, { "Sort by DOI Asc", doiAscending }, { "Sort by DOI Desc", doiDescending } }; }
From source file:io.github.karols.hocr4j.Page.java
/** * Finds a line that satisfies given predicate and according to the given comparator is the "largest". * If not found, returns <code>null</code>. * * @param comparatorForMaximizing comparator to choose the "largest" line * @param predicate predicate the found line has to satisfy * @return a line that satisfies the predicate, or <code>null</code> if there are none *//* w w w.j av a 2s.co m*/ @Nullable public Line findLine(@Nonnull Comparator<Line> comparatorForMaximizing, @Nonnull Predicate<Line> predicate) { Line result = null; for (Area a : areas) { Line l = a.findLine(comparatorForMaximizing, predicate); if (l != null) { if (result == null || comparatorForMaximizing.compare(l, result) > 0) { result = l; } } } return result; }
From source file:com.addthis.hydra.data.io.DiskBackedList2.java
/** * Sort the collection of elements using a standard external sort algorithm: sort each chunk of elements, then * merge the chunks into a new list, then switch to the new list. *///w w w . j a v a2 s . c o m public void sort(final Comparator<? super K> comp) { try { // Sort each chunk. Done if there is only one chunk. sortEachChunk(comp); if (chunks.size() <= 1) { return; } Comparator<Pair<K, Integer>> pairComp = new Comparator<Pair<K, Integer>>() { @Override public int compare(Pair<K, Integer> e1, Pair<K, Integer> e2) { return comp.compare(e1.getLeft(), e2.getLeft()); } }; // This heap stores the lowest remaining value from each chunk PriorityQueue<Pair<K, Integer>> heap = new PriorityQueue<>(chunks.size(), pairComp); ArrayList<Iterator> iterators = new ArrayList<>(chunks.size()); // Initialize the heap with one value per chunk close(); for (int i = 0; i < chunks.size(); i++) { Iterator<K> it = chunks.get(i).getChunkIterator(); iterators.add(i, it); if (it.hasNext()) { K elt = it.next(); if (elt != null) { heap.add(Pair.of(elt, i)); } } } // Make a new disk backed list to store sorted values. // When the number of chunks is large, the size of the output buffer needs to shrink to make up for the extra mem usage long storageMaxChunkSize = maxChunkSizeBytes / (1 + chunks.size() / 20); DiskBackedList2<K> storage = new DiskBackedList2<>(codec, storageMaxChunkSize, directory); // Repeatedly pull the smallest element from the heap while (!heap.isEmpty()) { Pair<K, Integer> leastElt = heap.poll(); storage.add(leastElt.getLeft()); @SuppressWarnings({ "unchecked" }) Iterator<K> polledIterator = iterators.get(leastElt.getRight()); if (polledIterator.hasNext()) { heap.add(Pair.of(polledIterator.next(), leastElt.getRight())); } } // Switch to the storage dbl's chunks storage.close(); chunks = storage.getChunks(); currentChunk = null; } catch (IOException io) { throw Throwables.propagate(io); } }
From source file:aarddict.Volume.java
Iterator<Entry> lookup(final LookupWord lookupWord, final Comparator<Entry> comparator) { if (lookupWord.isEmpty()) { return EMPTY_ITERATOR; }/*from w w w . j a va2 s.c om*/ final String section = lookupWord.section; final Entry lookupEntry = new Entry(this.getId(), lookupWord.word); final int initialIndex = binarySearch(this, lookupEntry, comparator); Iterator<Entry> iterator = new Iterator<Entry>() { int index = initialIndex; Entry nextEntry; { prepareNext(); } private void prepareNext() { if (index < header.indexCount) { Entry matchedEntry = get(index); nextEntry = (0 == comparator.compare(matchedEntry, lookupEntry)) ? matchedEntry : null; index++; } else { nextEntry = null; } } public boolean hasNext() { return nextEntry != null; } public Entry next() { Entry current = nextEntry; current.section = section; prepareNext(); return current; } public void remove() { throw new UnsupportedOperationException(); } }; return iterator; }
From source file:Graph.java
/** * Search the verticies for one with data. * /* ww w . ja v a2 s .co m*/ * @param data - * the vertex data to match * @param compare - * the comparator to perform the match * @return the first vertex with a matching data, null if no matches are found */ public Vertex<T> findVertexByData(T data, Comparator<T> compare) { Vertex<T> match = null; for (Vertex<T> v : verticies) { if (compare.compare(data, v.getData()) == 0) { match = v; break; } } return match; }
From source file:jetbrains.buildServer.clouds.azure.asm.connector.AzureApiConnector.java
public Promise<List<Image>, Throwable, Void> listImagesAsync() { return myManager.when(myClient.getVirtualMachineVMImagesOperations().listAsync()) .then(new DonePipe<VirtualMachineVMImageListResponse, List<Image>, Throwable, Void>() { @Override/*from w w w . j a v a2 s . c o m*/ public Promise<List<Image>, Throwable, Void> pipeDone( final VirtualMachineVMImageListResponse imagesList) { final List<Image> images = new ArrayList<Image>() { { for (VirtualMachineVMImageListResponse.VirtualMachineVMImage image : imagesList) { if (!"User".equals(image.getCategory())) continue; add(new Image(image.getName(), image.getLabel(), image.getOSDiskConfiguration().getOperatingSystem(), isImageGeneralized(image))); } } }; final Comparator<String> comparator = new AlphaNumericStringComparator(); Collections.sort(images, new Comparator<Image>() { @Override public int compare(Image o1, Image o2) { final String label1 = o1.getLabel(); final String label2 = o2.getLabel(); return comparator.compare(label1, label2); } }); return new DeferredObject<List<Image>, Throwable, Void>().resolve(images); } }); }
From source file:com.facebook.presto.accumulo.tools.TimestampCheckTask.java
private void getCountViaIndex(Connector connector, AccumuloTable table, AccumuloColumnHandle column, long timestamp, Set<Range> indexRanges, Set<ByteBuffer> indexRowIDs) throws Exception { LOG.info("Number of index ranges is " + indexRanges.size()); // Scan table with these entries Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator(); BatchScanner scanner = connector.createBatchScanner(table.getFullTableName(), auths, 10); scanner.setRanges(indexRanges);//from ww w .j av a2 s.c o m scanner.fetchColumn(new Text(column.getFamily().get()), new Text(column.getQualifier().get())); IteratorSetting iteratorSetting = new IteratorSetting(Integer.MAX_VALUE, TimestampFilter.class); TimestampFilter.setEnd(iteratorSetting, timestamp, true); scanner.addScanIterator(iteratorSetting); Set<ByteBuffer> values = new HashSet<>(indexRowIDs); Text text = new Text(); long numRows = 0; long outsideRange = 0; for (Entry<Key, Value> entry : scanner) { values.remove(ByteBuffer.wrap(entry.getKey().getRow(text).copyBytes())); byte[] timestampValue = entry.getValue().get(); if (comparator.compare(timestampValue, startBytes) >= 0 && comparator.compare(timestampValue, endBytes) <= 0) { ++numRows; } else { ++outsideRange; } } scanner.close(); LOG.info("Number of rows from data table via index is " + numRows); LOG.info("Number of rows from data table outside the time range is " + outsideRange); LOG.info("Number of rows in the index not scanned from the table is " + values.size()); if (values.size() > 0) { LOG.info("Sample records:"); values.stream().limit(10).forEach(x -> LOG.info(new String(x.array(), UTF_8))); } }