@Override public List<MessageModel> search(String geohash, int pageSize, int pageNum) { String prefixKey = geohash.substring(0, prefixLength); List<MessageModel> messageModelList = cache.get(prefixKey); List<MessageModel> messageResultModels = new ArrayList<>(); if (messageModelList != null) { if ((pageSize * pageNum) <= messageModelList.size()) { // 按时间进行降序 messageResultModels = messageModelList .parallelStream() .sorted(Comparator.comparing(MessageModel::getCreateTime).reversed()) .collect(Collectors.toList()) .subList(pageSize * (pageNum - 1), pageSize * pageNum); } else if (pageSize * (pageNum - 1) <= messageModelList.size()) { messageResultModels = messageModelList .parallelStream() .sorted(Comparator.comparing(MessageModel::getCreateTime).reversed()) .collect(Collectors.toList()) .subList(pageSize * (pageNum - 1), messageModelList.size()); } } return messageResultModels; }
@Test public void testNodeComparator2() { ICoverageNode d1 = new MockNode(18); ICoverageNode d2 = new MockNode(15); final Comparator<ICoverageNode> cmp = CounterComparator.TOTALITEMS.on(CounterEntity.LINE); assertEquals(0, cmp.compare(d1, d2), 0.0); }
@Test public void testEqualsPerformance() { boolean testEnabled = false; if (testEnabled) { final int ITERATIONS = 10000000; long start1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator(); comparator.compare(wrapper1.getData(), wrapper2.getData()); } System.out.println(System.currentTimeMillis() - start1 + "ms"); long start2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { Arrays.equals(wrapper1.getData(), wrapper2.getData()); } System.out.println(System.currentTimeMillis() - start2 + "ms"); long start3 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { FastByteComparisons.compareTo( wrapper1.getData(), 0, wrapper1.getData().length, wrapper2.getData(), 0, wrapper1.getData().length); } System.out.println(System.currentTimeMillis() - start3 + "ms"); } }
protected static void assertLesser( Comparator<ExhaustiveSearchNode> comparator, ExhaustiveSearchNode a, ExhaustiveSearchNode b) { assertTrue( "Node (" + a + ") must be lesser than node (" + b + ").", comparator.compare(a, b) < 0); assertTrue( "Node (" + b + ") must be greater than node (" + a + ").", comparator.compare(b, a) > 0); }
/** * Performs a binary search on the dataSet * * @param element is the value in to be searched for in dataSet * @return the index of dataSet that contains the element, or -1 if element does not exist in the * dataSet. */ public int binarySearch(E element) { if (element == null) return -1; Comparator<? super E> binaryComparator = comparator(); if (binaryComparator == null) binaryComparator = (Comparator<? super E>) Comparator.naturalOrder(); int lowerBound = 0; int upperBound = size - 1; int index = (lowerBound + upperBound) / 2; while (lowerBound <= upperBound) { int comparisonInt = binaryComparator.compare(element, dataSet[index]); if (comparisonInt == 0) { return index; } else if (comparisonInt > 0) { lowerBound = index + 1; index = (lowerBound + upperBound) / 2; } else { upperBound = index - 1; index = (lowerBound + upperBound) / 2; } } return -1; }
public static void main(String[] args) { Personne[] tab = { new Personne("thibault", "Rougier", 2001), new Personne("thomas", "Niesseron", 1987), new Personne("thifaine", "Mitenne", 1959), new Personne("maxime", "Forest", 1995), new Personne("jules", "Forest", 1995) }; System.out.println("--- Nes apres 1985 : "); Stream.of(tab) .filter(pp -> pp.getAnnee() > 1985) .forEach(pp -> System.out.print(pp.getPrenom() + ", ")); System.out.println("\n--- Nes avant 2000 :"); long nombre = Stream.of(tab) .filter(pp -> pp.getAnnee() < 2000) .sorted(Comparator.comparing(Personne::getNom)) .peek(pp -> System.out.print(pp.getNom() + " ")) .count(); System.out.println("\n Ils sont " + nombre); System.out.println("--- Tous tries sur nom + prenom : "); Stream.of(tab) .sorted(Comparator.comparing(pp -> pp.getNom() + pp.getPrenom())) .forEach(pp -> System.out.print("(" + pp.getNom() + ", " + pp.getPrenom() + ") ")); }
/** * Return a Comparator that will order the specified units in preferred unload order. If needed it * may also inspect the transport holding the units. */ public static Comparator<Unit> getUnloadableUnitsComparator( final List<Unit> units, final Route route, final PlayerID player) { // compare transports final Comparator<Unit> unloadableTransportsComparator = getUnloadableTransportsComparator(units, route, player, false); // if noTies is set, sort by hashcode so that result is deterministic final Comparator<Unit> movableUnitsComparator = getMovableUnitsComparator(units, route); return (u1, u2) -> { final Unit t1 = TripleAUnit.get(u1).getTransportedBy(); final Unit t2 = TripleAUnit.get(u2).getTransportedBy(); // check if unloadable units are in a transport if (t1 != null && t2 == null) { return -1; } if (t1 == null && t2 != null) { return 1; } if (t1 != null && t2 != null) { final int compareTransports = unloadableTransportsComparator.compare(t1, t2); if (compareTransports != 0) { return compareTransports; } } // we are sorting air units, or no difference found yet // if noTies is set, sort by hashcode so that result is deterministic return movableUnitsComparator.compare(u1, u2); }; }
public static <T1, T2, T3, T4> Comparator<Tuple4<T1, T2, T3, T4>> comparator( Comparator<? super T1> t1Comp, Comparator<? super T2> t2Comp, Comparator<? super T3> t3Comp, Comparator<? super T4> t4Comp) { return (Comparator<Tuple4<T1, T2, T3, T4>> & Serializable) (t1, t2) -> { final int check1 = t1Comp.compare(t1._1, t2._1); if (check1 != 0) { return check1; } final int check2 = t2Comp.compare(t1._2, t2._2); if (check2 != 0) { return check2; } final int check3 = t3Comp.compare(t1._3, t2._3); if (check3 != 0) { return check3; } final int check4 = t4Comp.compare(t1._4, t2._4); if (check4 != 0) { return check4; } // all components are equal return 0; }; }
public int compare(T m1, T m2) { for (Comparator<? super T> comparator : comparators) { int comparisonResult = comparator.compare(m1, m2); if (comparisonResult != 0) return comparisonResult; } return 0; }
/** {@inheritDoc} */ @Override protected void iterateSimplex(final Comparator<RealPointValuePair> comparator) throws FunctionEvaluationException, OptimizationException, IllegalArgumentException { while (true) { incrementIterationsCounter(); // save the original vertex final RealPointValuePair[] original = simplex; final RealPointValuePair best = original[0]; // perform a reflection step final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator); if (comparator.compare(reflected, best) < 0) { // compute the expanded simplex final RealPointValuePair[] reflectedSimplex = simplex; final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator); if (comparator.compare(reflected, expanded) <= 0) { // accept the reflected simplex simplex = reflectedSimplex; } return; } // compute the contracted simplex final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator); if (comparator.compare(contracted, best) < 0) { // accept the contracted simplex return; } } }
@Test public void testNext() { boolean expected = true; EasyMock.expect(peekIterator.hasNext()).andReturn(expected).times(4); String defaultString = "S1"; String resString = "S2"; EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(binaryFn.apply(EasyMock.eq(defaultString), EasyMock.isNull())) .andReturn(resString); EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(0); EasyMock.expect(peekIterator.next()).andReturn(defaultString); EasyMock.expect(binaryFn.apply(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(resString); EasyMock.expect(comparator.compare(EasyMock.eq(resString), EasyMock.eq(defaultString))) .andReturn(1); EasyMock.replay(peekIterator); EasyMock.replay(binaryFn); EasyMock.replay(comparator); String actual = testingIterator.next(); Assert.assertEquals(resString, actual); EasyMock.verify(peekIterator); EasyMock.verify(comparator); EasyMock.verify(binaryFn); }
@Test public void testUnsignedComparator() { Comparator<Integer> cmp = (x, y) -> Integer.compareUnsigned(x, y); assertEquals(0, cmp.compare(0, 0)); assertEquals(1, cmp.compare(-100, 100)); assertEquals(-1, cmp.compare(100, -100)); }
@Override public RMContainer preemptContainer() { RMContainer toBePreempted = null; // If this queue is not over its fair share, reject if (!preemptContainerPreCheck()) { return toBePreempted; } if (LOG.isDebugEnabled()) { LOG.debug( "Queue " + getName() + " is going to preempt a container " + "from its applications."); } // Choose the app that is most over fair share Comparator<Schedulable> comparator = policy.getComparator(); FSAppAttempt candidateSched = null; for (FSAppAttempt sched : runnableApps) { if (candidateSched == null || comparator.compare(sched, candidateSched) > 0) { candidateSched = sched; } } // Preempt from the selected app if (candidateSched != null) { toBePreempted = candidateSched.preemptContainer(); } return toBePreempted; }
@Override protected int partition(Comparator<Object> c, int p, int r) { char[] x = keyTable[p]; Object temp = null; int i = p; int j = r; while (true) { while (c.compare(keyTable[j], x) > 0) { j--; } if (i < j) { while (c.compare(keyTable[i], x) < 0) { i++; } } if (i < j) { temp = keyTable[j]; keyTable[j] = keyTable[i]; keyTable[i] = (char[]) temp; temp = valueTable[j]; valueTable[j] = valueTable[i]; valueTable[i] = temp; } else { return j; } } }
/** * Sort a range in the array * * @param <T> The data type of the array * @param S The array * @param start The index of the first element in the range to sort * @param end Unused, instead start + 3 is always the last element in the range. * @return The array */ @Override public <T> T[] sort(T[] S, int start, int end, Comparator<T> comparator) { if (comparator == null) comparator = naturalOrderingComparator; int i0 = start; int i1 = start + 1; int i2 = start + 2; int i3 = start + 3; if (comparator.compare(S[i0], S[i1]) > i0) { permutator.swap(S, i0, i1); } if (comparator.compare(S[i2], S[i3]) > i0) { permutator.swap(S, i2, i3); } if (comparator.compare(S[i1], S[i3]) > i0) { // This establishes the maximum into S[i3] permutator.swap(S, i1, i3); } if (comparator.compare(S[i0], S[i2]) > i0) { // This establishes the minimum into S[i0] permutator.swap(S, i0, i2); } if (comparator.compare(S[i1], S[i2]) > i0) { // This sorts the remaining two elements permutator.swap(S, i1, i2); } return S; }
/** {@inheritDoc} */ @Override public List<Row> postReconciliationProcessing(List<IndexExpression> clause, List<Row> rows) { int startSize = rows.size(); long startTime = System.currentTimeMillis(); // Remove duplicates TreeSet<Row> set = new TreeSet<>(rowService.comparator()); set.addAll(rows); List<Row> result = new ArrayList<>(set); // Sort Search search = search(clause); Comparator<Row> comparator = rowService.comparator(search); Collections.sort(result, comparator); String comparatorName = comparator.getClass().getSimpleName(); int endSize = result.size(); long endTime = System.currentTimeMillis() - startTime; Log.debug( "Sorted %d rows to %d with comparator %s in %d ms\n", startSize, endSize, comparatorName, endTime); return result; }
private void sortTail() { // size > limit here T[] d = data; int l = limit, s = size; Comparator<? super T> cmp = comparator; Arrays.sort(d, l, s, cmp); if (cmp.compare(d[s - 1], d[0]) < 0) { // Common case: descending sequence // Assume size - limit <= limit here System.arraycopy(d, 0, d, s - l, 2 * l - s); System.arraycopy(d, l, d, 0, s - l); } else { // Merge presorted 0..limit-1 and limit..size-1 @SuppressWarnings("unchecked") T[] buf = (T[]) new Object[l]; int i = 0, j = l, k = 0; // d[l-1] is guaranteed to be the worst element, thus no need to // check it while (i < l - 1 && k < l && j < s) { if (cmp.compare(d[i], d[j]) <= 0) { buf[k++] = d[i++]; } else { buf[k++] = d[j++]; } } if (k < l) { System.arraycopy(d, i < l - 1 ? i : j, d, k, l - k); } System.arraycopy(buf, 0, d, 0, k); } size = l; }
@Test public void testCustomMatcher() { Comparator mock = mock(Comparator.class); mock.compare("Hello", "World"); mock.compare("Foo", "Bar"); mock.compare("Foo", null); BasicMatcher<Object> myFooBarMatcher = new BasicMatcher<Object>() { @Override public boolean matches(Object value) { return "Foo".equals(value) || "Bar".equals(value); } @Override public Class<Object> getType() { return Object.class; } @Override protected String asString() { return "(Foo or Bar)"; } }; verifyOnce().on(mock).compare(match(myFooBarMatcher), match(myFooBarMatcher)); }
public void drawFeatures(Graphics2D graphics, final StreamingRenderer renderer, String layerId) throws IOException, FactoryException, NoninvertibleTransformException, SchemaException, TransformException { // 1) init all the readers and the lfts associated to them (one at a time to avoid deadlock) // and create one RenderableFeature for each // 2) process all the features one z-level at a time, backtracking if there are multiple // fts for a certain layer. // a listener passed around to stop data reading/painting if rendering stop request is // issued ProgressListener cancellationListener = new DefaultProgressListener() { public boolean isCanceled() { return renderer.renderingStopRequested; }; }; List<ZGroupLayerPainter> painters = null; try { painters = buildLayerPainters(graphics, renderer, layerId, cancellationListener); if (painters.isEmpty()) { return; } // get a comparator to find the first key to paint Comparator<SortKey> comparator = SortKey.buildComparator(painters.get(0).sortBy); // paint all the features as we can SortKey previousKey = null; while (!painters.isEmpty()) { SortKey smallestKey = getSmallestKey(painters, comparator); if (previousKey == null) { previousKey = smallestKey; } else if (comparator.compare(previousKey, smallestKey) >= 0) { throw new IllegalStateException( "The sorted rendering moved from a set of " + "sort attributes, to one that's equal or greater, this is unexpected, " + "bailing out to avoid an infinite loop"); } else { previousKey = smallestKey; } for (Iterator it = painters.iterator(); it.hasNext(); ) { ZGroupLayerPainter painter = (ZGroupLayerPainter) it.next(); painter.paintKey(smallestKey); // if the painter is done, close it if (painter.complete()) { painter.close(); it.remove(); } } } } finally { if (painters != null) { for (ZGroupLayerPainter painter : painters) { painter.close(); } } } }
public void testProcessReportsComparator() throws Exception { final Comparator<ProcessReports> comparator = new ProcessControl.ProcessReportsComparator(); final AgentIdentity agentIdentity1 = new StubAgentIdentity("my agent"); final AgentProcessReport agentProcessReport1 = new StubAgentProcessReport(agentIdentity1, AgentProcessReport.STATE_RUNNING); final RandomStubFactory<ProcessReports> processReportsStubFactory1 = RandomStubFactory.create(ProcessReports.class); final ProcessReports processReports1 = processReportsStubFactory1.getStub(); processReportsStubFactory1.setResult("getAgentProcessReport", agentProcessReport1); assertEquals(0, comparator.compare(processReports1, processReports1)); final AgentProcessReport agentProcessReport2 = new StubAgentProcessReport(agentIdentity1, AgentProcessReport.STATE_FINISHED); final RandomStubFactory<ProcessReports> processReportsStubFactory2 = RandomStubFactory.create(ProcessReports.class); final ProcessReports processReports2 = processReportsStubFactory2.getStub(); processReportsStubFactory2.setResult("getAgentProcessReport", agentProcessReport2); assertEquals(0, comparator.compare(processReports2, processReports2)); assertTrue(comparator.compare(processReports1, processReports2) < 0); assertTrue(comparator.compare(processReports2, processReports1) > 0); }
private Comparator<StrBean> getComparator(SortOrder<String> so) { Comparator<StrBean> comparator = propertyToComparatorMap.get(so.getSorted()); if (so.getDirection() == SortDirection.DESCENDING) { comparator = comparator.reversed(); } return comparator; }
/** * Either adds a value to set or does nothing if value is already present. * * @param val Value to add. * @return The instance of value from this set or {@code null} if value was added. */ @Nullable public V addx(V val) { A.notNull(val, "val"); if (comp == null) { for (V v : vals) if (v.equals(val)) return v; vals.add(val); return null; } if (strict) { for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) return v; int c = comp.compare(v, val); if (c == 0) throw new IllegalStateException("Inconsistent equals and compare methods."); if (c > 0) { // Back up. it.previous(); it.add(val); return null; } } vals.add(val); return null; } // Full scan first. for (V v : vals) if (v.equals(val)) return v; for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); if (comp.compare(v, val) > 0) { do { // Back up. v = it.previous(); } while (comp.compare(v, val) == 0); it.add(val); return null; } } vals.add(val); return null; }
/** * Compare two file lists for files which have been created, modified or deleted. * * @param parent The parent entry * @param previous The original list of files * @param files The current list of files */ private void checkAndNotify(FileEntry parent, FileEntry[] previous, File[] files) { int c = 0; FileEntry[] current = files.length > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (FileEntry entry : previous) { while (c < files.length && comparator.compare(entry.getFile(), files[c]) > 0) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); c++; } if (c < files.length && comparator.compare(entry.getFile(), files[c]) == 0) { doMatch(entry, files[c]); checkAndNotify(entry, entry.getChildren(), listFiles(files[c])); current[c] = entry; c++; } else { checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); doDelete(entry); } } for (; c < files.length; c++) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); } parent.setChildren(current); }
void sort(int from, int to, Comparator<T> cmp) { int width = to - from; if (to - from <= 15) selectionSort(from, to, cmp); else { T pivot = myarray[rand.nextInt(width) + from]; T tmp; int i = from - 1; int j = to; for (; ; ) { do i++; while (cmp.compare(myarray[i], pivot) < 0); do j--; while (cmp.compare(pivot, myarray[j]) < 0); if (i >= j) break; tmp = myarray[i]; myarray[i] = myarray[j]; myarray[j] = tmp; } sort(from, i, cmp); sort(i, to, cmp); } }
@Test public void testUnsignedComparatorMRef() { Comparator<Integer> cmp = Integer::compareUnsigned; assertEquals(0, cmp.compare(0, 0)); assertEquals(1, cmp.compare(-100, 100)); assertEquals(-1, cmp.compare(100, -100)); }
public TestResult matchMessage(String actual, String expected) { if (actual == null) return TestResult.fail("NULL"); if (actual.equals(replaceSymbols(expected))) return TestResult.pass(replaceSymbolsWithFullExpansion(expected)); Comparator c = new Comparator(actual, expected); return c.evaluate(); }
private GeneralRange( Comparator<? super T> comparator, boolean hasLowerBound, @Nullable T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @Nullable T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); this.hasLowerBound = hasLowerBound; this.hasUpperBound = hasUpperBound; this.lowerEndpoint = lowerEndpoint; this.lowerBoundType = checkNotNull(lowerBoundType); this.upperEndpoint = upperEndpoint; this.upperBoundType = checkNotNull(upperBoundType); if (hasLowerBound) { comparator.compare(lowerEndpoint, lowerEndpoint); } if (hasUpperBound) { comparator.compare(upperEndpoint, upperEndpoint); } if (hasLowerBound && hasUpperBound) { int cmp = comparator.compare(lowerEndpoint, upperEndpoint); // be consistent with Range checkArgument( cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint); if (cmp == 0) { checkArgument(lowerBoundType != OPEN | upperBoundType != OPEN); } } }
public DatabaseConfig getConfig__wrappee__base() throws DatabaseException { DatabaseConfig showConfig = configuration.cloneConfig(); Comparator btComp = (databaseImpl == null ? null : databaseImpl.getBtreeComparator()); Comparator dupComp = (databaseImpl == null ? null : databaseImpl.getDuplicateComparator()); showConfig.setBtreeComparator(btComp == null ? null : btComp.getClass()); showConfig.setDuplicateComparator(dupComp == null ? null : dupComp.getClass()); return showConfig; }
static int unsafeCompare(Comparator<?> comparator, Object a, Object b) { // Pretend the comparator can compare anything. If it turns out it can't // compare a and b, we should get a CCE on the subsequent line. Only methods // that are spec'd to throw CCE should call this. @SuppressWarnings("unchecked") Comparator<Object> unsafeComparator = (Comparator<Object>) comparator; return unsafeComparator.compare(a, b); }
@Test public void testNodeComparator1() { ICoverageNode d1 = new MockNode(18); ICoverageNode d2 = new MockNode(15); final Comparator<ICoverageNode> cmp = CounterComparator.TOTALITEMS.on(CounterEntity.INSTRUCTION); assertTrue(cmp.compare(d1, d2) > 0); }