Java Code Examples for java.util.Comparator#comparingLong()

The following examples show how to use java.util.Comparator#comparingLong() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClockManager.java    From plugins with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks to ensure the timers are in the correct order.
 * If they are not, sort them and rebuild the clock panel
 *
 * @return whether the timer order was changed or not
 */
public boolean checkTimerOrder()
{
	SortOrder sortOrder = config.sortOrder();
	if (sortOrder != SortOrder.NONE)
	{
		Comparator<Timer> comparator = Comparator.comparingLong(Timer::getDisplayTime);
		if (sortOrder == SortOrder.DESC)
		{
			comparator = comparator.reversed();
		}

		if (!Comparators.isInOrder(timers, comparator))
		{
			timers.sort(comparator);
			SwingUtilities.invokeLater(clockTabPanel::rebuild);
			return true;
		}
	}
	return false;
}
 
Example 2
Source File: MultiStreamMergeTest.java    From blog-sample with Apache License 2.0 6 votes vote down vote up
@Test
public void queryOrderNew() {
    long start = Utils.now();

    Stream<Order> stream = sourceOrder.stream();

    stream = stream.filter(e -> e.getAmount() > 0);

    if(startId > 0) {
        stream = stream.filter(e -> e.getId() >= startId);
    }
    if(endId > 0) {
        stream = stream.filter(e -> e.getId() < endId);
    }

    Comparator<Order> comparator = Comparator.comparingLong(Order::getId);
    if(!isAsc) {
        comparator = comparator.reversed();
    }

    List<Order> result = stream.limit(limit).sorted(comparator).collect(Collectors.toList());

    System.out.println("queryOrderNew: " + Utils.diff(start));
}
 
Example 3
Source File: TextReporter.java    From caffeine with Apache License 2.0 6 votes vote down vote up
private Comparator<PolicyStats> makeComparator() {
  switch (settings.report().sortBy().toLowerCase(US)) {
    case "policy":
      return Comparator.comparing(PolicyStats::name);
    case "hit rate":
      return Comparator.comparingDouble(PolicyStats::hitRate);
    case "hits":
      return Comparator.comparingLong(PolicyStats::hitCount);
    case "misses":
      return Comparator.comparingLong(PolicyStats::missCount);
    case "evictions":
      return Comparator.comparingLong(PolicyStats::evictionCount);
    case "admit rate":
      return Comparator.comparingLong(PolicyStats::admissionCount);
    case "steps":
      return Comparator.comparingLong(PolicyStats::operationCount);
    case "time":
      return Comparator.comparingLong(stats -> stats.stopwatch().elapsed(TimeUnit.NANOSECONDS));
    default:
      throw new IllegalArgumentException("Unknown sort order: " + settings.report().sortBy());
  }
}
 
Example 4
Source File: ClockManager.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Checks to ensure the timers are in the correct order.
 * If they are not, sort them and rebuild the clock panel
 *
 * @return whether the timer order was changed or not
 */
public boolean checkTimerOrder()
{
	SortOrder sortOrder = config.sortOrder();
	if (sortOrder != SortOrder.NONE)
	{
		Comparator<Timer> comparator = Comparator.comparingLong(Timer::getDisplayTime);
		if (sortOrder == SortOrder.DESC)
		{
			comparator = comparator.reversed();
		}

		if (!Comparators.isInOrder(timers, comparator))
		{
			timers.sort(comparator);
			SwingUtilities.invokeLater(clockTabPanel::rebuild);
			return true;
		}
	}
	return false;
}
 
Example 5
Source File: ForestSpanningTree.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void decideTheNextLayer(Collection<LayoutEntity> currentLayer, SegmentInfo segment) {
    // After built, we know each cuboid's size.
    // Then we will find each cuboid's children.
    // Smaller cuboid has smaller cost, and has higher priority when finding children.
    Comparator<LayoutEntity> c1 = Comparator.comparingLong(o -> o.rows);

    // for deterministic
    Comparator<LayoutEntity> c2 = Comparator.comparingLong(LayoutEntity::getId);

    List<LayoutEntity> orderedIndexes = currentLayer.stream() //
            .sorted(c1.thenComparing(c2)) //
            .collect(Collectors.toList()); //

    orderedIndexes.forEach(index -> {
        adjustTree(index, segment);

        logger.info("Adjust spanning tree." + //
                        " Current index entity: {}." + //
                        " Its children: {}\n" //
                , index.getId() //
                , Arrays.toString(getChildrenByIndexPlan(index).stream() //
                        .map(LayoutEntity::getId).toArray())//
        );
    });

}
 
Example 6
Source File: Java8ComparatorUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenComparingLong_thenSortedByMobile() {
    Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
    Arrays.sort(employees, employeeMobileComparator);
    // System.out.println(Arrays.toString(employees));
    assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
}
 
Example 7
Source File: BookKeeperLogTests.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the ability to retry writes when Bookies fail.
 */
@Test
public void testAppendTransientBookieFailure() throws Exception {
    TreeMap<LogAddress, byte[]> writeData = new TreeMap<>(Comparator.comparingLong(LogAddress::getSequence));
    try (DurableDataLog log = createDurableDataLog()) {
        log.initialize(TIMEOUT);

        val dataList = new ArrayList<byte[]>();
        val futures = new ArrayList<CompletableFuture<LogAddress>>();

        try {
            // Suspend a bookie (this will trigger write errors).
            stopFirstBookie();

            // Issue appends in parallel, without waiting for them.
            int writeCount = getWriteCount();
            for (int i = 0; i < writeCount; i++) {
                byte[] data = getWriteData();
                futures.add(log.append(new CompositeByteArraySegment(data), TIMEOUT));
                dataList.add(data);
            }
        } finally {
            // Resume the bookie with the appends still in flight.
            restartFirstBookie();
        }

        // Wait for all writes to complete, then reassemble the data in the order set by LogAddress.
        val addresses = Futures.allOfWithResults(futures).join();
        for (int i = 0; i < dataList.size(); i++) {
            writeData.put(addresses.get(i), dataList.get(i));
        }
    }

    // Verify data.
    try (DurableDataLog log = createDurableDataLog()) {
        log.initialize(TIMEOUT);
        verifyReads(log, writeData);
    }
}
 
Example 8
Source File: BasicTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void testLongComparator() {
    Thing[] things = new Thing[longValues.length];
    for (int i=0; i<longValues.length; i++)
        things[i] = new Thing(0, longValues[i], 0.0, null);
    Comparator<Thing> comp = Comparator.comparingLong(new ToLongFunction<Thing>() {
        @Override
        public long applyAsLong(Thing thing) {
            return thing.getLongField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 9
Source File: BasicTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void testLongComparator() {
    Thing[] things = new Thing[longValues.length];
    for (int i=0; i<longValues.length; i++)
        things[i] = new Thing(0, longValues[i], 0.0, null);
    Comparator<Thing> comp = Comparator.comparingLong(new ToLongFunction<Thing>() {
        @Override
        public long applyAsLong(Thing thing) {
            return thing.getLongField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 10
Source File: BucketService.java    From pravega with Apache License 2.0 5 votes vote down vote up
BucketService(BucketStore.ServiceType serviceType, int bucketId, ScheduledExecutorService executor,
              int maxConcurrentExecutions, Duration executionPeriod, BucketWork bucketWork) {
    this.serviceType = serviceType;
    this.bucketId = bucketId;
    this.executor = executor;
    this.notifications = new BlockingDrainingQueue<>();
    this.serviceStartFuture = new CompletableFuture<>();
    this.notificationLoop = new AtomicReference<>(CompletableFuture.completedFuture(null));
    this.workerLoop = new AtomicReference<>(CompletableFuture.completedFuture(null));
    this.availableSlots = maxConcurrentExecutions;
    this.knownStreams = new HashSet<>();
    this.workQueue = new PriorityQueue<>(Comparator.comparingLong(x -> x.nextExecutionTimeInMillis));
    this.executionPeriod = executionPeriod;
    this.bucketWork = bucketWork;
}
 
Example 11
Source File: ClientRegistrationService.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected ClientTokens doGetClientIssuedTokens(Client c) {
    Comparator<AccessToken> tokenComp = Comparator.comparingLong(AccessToken::getIssuedAt);
    UserSubject subject = new OidcUserSubject(getUserName());
    Collection<ServerAccessToken> accessTokens = new TreeSet<>(tokenComp);
    accessTokens.addAll(dataProvider.getAccessTokens(c, subject));
    Collection<RefreshToken> refreshTokens = new TreeSet<>(tokenComp);
    refreshTokens.addAll(dataProvider.getRefreshTokens(c, subject));
    return new ClientTokens(c, accessTokens, refreshTokens);
}
 
Example 12
Source File: BasicTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void testLongComparator() {
    Thing[] things = new Thing[longValues.length];
    for (int i=0; i<longValues.length; i++)
        things[i] = new Thing(0, longValues[i], 0.0, null);
    Comparator<Thing> comp = Comparator.comparingLong(new ToLongFunction<Thing>() {
        @Override
        public long applyAsLong(Thing thing) {
            return thing.getLongField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 13
Source File: BasicTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testLongComparator() {
    Thing[] things = new Thing[longValues.length];
    for (int i=0; i<longValues.length; i++)
        things[i] = new Thing(0, longValues[i], 0.0, null);
    Comparator<Thing> comp = Comparator.comparingLong(new ToLongFunction<Thing>() {
        @Override
        public long applyAsLong(Thing thing) {
            return thing.getLongField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 14
Source File: BasicTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testLongComparator() {
    Thing[] things = new Thing[longValues.length];
    for (int i=0; i<longValues.length; i++)
        things[i] = new Thing(0, longValues[i], 0.0, null);
    Comparator<Thing> comp = Comparator.comparingLong(new ToLongFunction<Thing>() {
        @Override
        public long applyAsLong(Thing thing) {
            return thing.getLongField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example 15
Source File: ComparatorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testComparingLong() {
    Comparator<Item> comparator = Comparator.comparingLong(Item::getOrderAsLong);
    checkComparison(comparator, orderedItems);
}
 
Example 16
Source File: ResourceRequestState.java    From samza with Apache License 2.0 4 votes vote down vote up
DelayedRequestQueue() {
  super(Comparator.comparingLong(request -> request.getRequestTimestamp().toEpochMilli()));
}
 
Example 17
Source File: BoundedLocalCache.java    From caffeine with Apache License 2.0 4 votes vote down vote up
Map<K, V> sortedByWriteTime(int limit, boolean ascending) {
  Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getWriteTime);
  Iterator<Node<K, V>> iterator = cache.data.values().stream().parallel().sorted(
      ascending ? comparator : comparator.reversed()).limit(limit).iterator();
  return cache.fixedSnapshot(() -> iterator, limit, transformer);
}
 
Example 18
Source File: MessageSetImpl.java    From Javacord with Apache License 2.0 3 votes vote down vote up
/**
 * Requests the messages from Discord, sorted by their id.
 *
 * @param channel The channel of which to get messages from.
 * @param limit The limit of messages to get.
 * @param before Get messages before the message with this id.
 * @param after Get messages after the message with this id.
 * @param reversed If {@code true}, get from oldest to newest, otherwise from newest to oldest.
 * @return The JSON nodes.
 */
private static List<JsonNode> requestAsSortedJsonNodes(
        TextChannel channel, int limit, long before, long after, boolean reversed) {
    List<JsonNode> messageJsonNodes = requestAsJsonNodes(channel, limit, before, after);
    Comparator<JsonNode> idComparator = Comparator.comparingLong(jsonNode -> jsonNode.get("id").asLong());
    messageJsonNodes.sort(reversed ? idComparator.reversed() : idComparator);
    return messageJsonNodes;
}
 
Example 19
Source File: MessageSetImpl.java    From Javacord with Apache License 2.0 3 votes vote down vote up
/**
 * Requests the messages from Discord, sorted by their id.
 *
 * @param channel The channel of which to get messages from.
 * @param limit The limit of messages to get.
 * @param before Get messages before the message with this id.
 * @param after Get messages after the message with this id.
 * @param reversed If {@code true}, get from oldest to newest, otherwise from newest to oldest.
 * @return The JSON nodes.
 */
private static List<JsonNode> requestAsSortedJsonNodes(
        TextChannel channel, int limit, long before, long after, boolean reversed) {
    List<JsonNode> messageJsonNodes = requestAsJsonNodes(channel, limit, before, after);
    Comparator<JsonNode> idComparator = Comparator.comparingLong(jsonNode -> jsonNode.get("id").asLong());
    messageJsonNodes.sort(reversed ? idComparator.reversed() : idComparator);
    return messageJsonNodes;
}
 
Example 20
Source File: CachedFsClient.java    From datakernel with Apache License 2.0 2 votes vote down vote up
/**
 * Default {@link Comparator} to compare files by size
 *
 * @return filesize {@link Comparator}
 */
public static Comparator<FullCacheStat> sizeCompare() {
	return Comparator.comparingLong(fullCacheStat -> -fullCacheStat.getFileMetadata().getSize());
}