下面列出了java.util.Comparator#comparingLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
@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));
}
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());
}
}
/**
* 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;
}
@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())//
);
});
}
@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));
}
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);
}
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);
}
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;
}
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);
}
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);
}
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);
}
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);
}
/**
* 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);
}
}
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);
}
DelayedRequestQueue() {
super(Comparator.comparingLong(request -> request.getRequestTimestamp().toEpochMilli()));
}
public void testComparingLong() {
Comparator<Item> comparator = Comparator.comparingLong(Item::getOrderAsLong);
checkComparison(comparator, orderedItems);
}
/**
* 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;
}
/**
* 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;
}
/**
* Default {@link Comparator} to compare files by size
*
* @return filesize {@link Comparator}
*/
public static Comparator<FullCacheStat> sizeCompare() {
return Comparator.comparingLong(fullCacheStat -> -fullCacheStat.getFileMetadata().getSize());
}