java.util.stream.Stream.max()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.5k)|赞(0)|评价(0)|浏览(299)

本文整理了Java中java.util.stream.Stream.max()方法的一些代码示例,展示了Stream.max()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.max()方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:max

Stream.max介绍

[英]Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.

This is a terminal operation.
[中]根据提供的比较器返回此流的最大元素。这是reduction的一个特例。
这是一个terminal operation

代码示例

代码示例来源:origin: apache/incubator-druid

private static ImmutableWorkerInfo selectFromEligibleWorkers(final Map<String, ImmutableWorkerInfo> eligibleWorkers)
{
 return eligibleWorkers.values().stream().max(
   Comparator.comparing(ImmutableWorkerInfo::getCurrCapacityUsed)
 ).orElse(null);
}

代码示例来源:origin: apache/incubator-druid

private static ImmutableWorkerInfo selectFromEligibleWorkers(final Map<String, ImmutableWorkerInfo> eligibleWorkers)
{
 return eligibleWorkers.values().stream().max(
   Comparator.comparing(ImmutableWorkerInfo::getAvailableCapacity)
 ).orElse(null);
}

代码示例来源:origin: ben-manes/caffeine

@Override Node select(List<Node> sample, Random random, long tick) {
  return sample.stream().max((first, second) ->
    Long.compare(first.frequency, second.frequency)).get();
 }
},

代码示例来源:origin: ben-manes/caffeine

@Override Node select(List<Node> sample, Random random, long tick) {
  return sample.stream().max((first, second) ->
    Long.compare(first.accessTime, second.accessTime)).get();
 }
},

代码示例来源:origin: apache/storm

private static int getMaxTaskId(Map<String, List<Integer>> componentToSortedTasks) {
  int maxTaskId = -1;
  for (List<Integer> integers : componentToSortedTasks.values()) {
    if (!integers.isEmpty()) {
      int tempMax = integers.stream().max(Integer::compareTo).get();
      if (tempMax > maxTaskId) {
        maxTaskId = tempMax;
      }
    }
  }
  return maxTaskId;
}

代码示例来源:origin: neo4j/neo4j

public void forEach( BiConsumer<String,URI> consumer )
{
  entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
      .forEach( ( key, list ) -> list.stream()
          .max( Comparator.comparing( e -> e.precedence ) )
          .ifPresent( e -> consumer.accept( key, e.uri ) ) );
}

代码示例来源:origin: SonarSource/sonarqube

private static Changeset computeLatestChangeset(Map<Integer, Changeset> lineChangesets) {
 return lineChangesets.values().stream().max(Comparator.comparingLong(Changeset::getDate))
  .orElseThrow(() -> new IllegalStateException("Expecting at least one Changeset to be present"));
}

代码示例来源:origin: prestodb/presto

@VisibleForTesting
static Estimate calculateDistinctValuesCount(List<HiveColumnStatistics> columnStatistics)
{
  return columnStatistics.stream()
      .map(MetastoreHiveStatisticsProvider::getDistinctValuesCount)
      .filter(OptionalLong::isPresent)
      .map(OptionalLong::getAsLong)
      .peek(distinctValuesCount -> verify(distinctValuesCount >= 0, "distinctValuesCount must be greater than or equal to zero"))
      .max(Long::compare)
      .map(Estimate::of)
      .orElse(Estimate.unknown());
}

代码示例来源:origin: apache/storm

public static <V> ArrayList<V> convertToArray(Map<Integer, V> srcMap, int start) {
  Set<Integer> ids = srcMap.keySet();
  Integer largestId = ids.stream().max(Integer::compareTo).get();
  int end = largestId - start;
  ArrayList<V> result = new ArrayList<>(Collections.nCopies(end + 1, null)); // creates array[largestId+1] filled with nulls
  for (Map.Entry<Integer, V> entry : srcMap.entrySet()) {
    int id = entry.getKey();
    if (id < start) {
      LOG.debug("Entry {} will be skipped it is too small {} ...", id, start);
    } else {
      result.set(id - start, entry.getValue());
    }
  }
  return result;
}

代码示例来源:origin: Alluxio/alluxio

/**
  * Gets the align format according to the longest mount point/under storage path.
  * @param mountTable the mount table to get information from
  * @return the align format for printing mounted info
  */
 private static String getAlignFormat(Map<String, MountPointInfo> mountTable) {
  int mountPointLength = mountTable.entrySet().stream().map(w -> w.getKey().length())
    .max(Comparator.comparing(Integer::intValue)).get();
  int usfLength = mountTable.entrySet().stream().map(w -> w.getValue().getUfsUri().length())
    .max(Comparator.comparing(Integer::intValue)).get();

  String leftAlignFormat = "%-" + usfLength + "s  on  %-" + mountPointLength
    + "s  (%s, capacity=%s, used=%s, %sread-only, %sshared, ";
  return leftAlignFormat;
 }
}

代码示例来源:origin: apache/hbase

Optional<ServerName> getLargestQueueFromServersNotCompacting() {
 lock.readLock().lock();
 try {
  return compactionQueues.entrySet().stream()
    .filter(entry -> !compactingServers.contains(entry.getKey()))
    .max(Map.Entry.comparingByValue(
     (o1, o2) -> Integer.compare(o1.size(), o2.size()))).map(Map.Entry::getKey);
 } finally {
  lock.readLock().unlock();
 }
}

代码示例来源:origin: wildfly/wildfly

private static void printStats(Map<String, List<Long>> results) {
    for (Map.Entry<String, List<Long>> entry : results.entrySet()) {
      System.out.printf("Results for %s%n", entry.getKey());
      System.out.printf("Min merge time=%d%n", entry.getValue().stream().min(Long::compare).get());
      System.out.printf("Max merge time=%d%n", entry.getValue().stream().max(Long::compare).get());
      System.out.printf("Avg merge time=%s%n", entry.getValue().stream().mapToLong(x -> x).average().getAsDouble());
      System.out.printf("===================================================================%n");
    }
  }
}

代码示例来源:origin: apache/ignite

/**
 * Print cache command arguments usage.
 *
 * @param paramsDesc Cache command arguments description.
 * @param indentsNum Number of indents.
 */
private void usageCacheParams(Map<String, String> paramsDesc, int indentsNum) {
  int maxParamLen = paramsDesc.keySet().stream().max(Comparator.comparingInt(String::length)).get().length();
  for (Map.Entry<String, String> param : paramsDesc.entrySet())
    log(i(extendToLen(param.getKey(), maxParamLen) + INDENT + "- " + param.getValue(), indentsNum));
}

代码示例来源:origin: SonarSource/sonarqube

private static Optional<Changeset> getLatestChangeset(Component component, ScmInfo scmInfo, DefaultIssue issue) {
 Optional<Changeset> mostRecentChangeset = IssueLocations.allLinesFor(issue, component.getUuid())
  .filter(scmInfo::hasChangesetForLine)
  .mapToObj(scmInfo::getChangesetForLine)
  .max(Comparator.comparingLong(Changeset::getDate));
 if (mostRecentChangeset.isPresent()) {
  return mostRecentChangeset;
 }
 return Optional.of(scmInfo.getLatestChangeset());
}

代码示例来源:origin: apache/hbase

public int getPriority() {
  Optional<Action> result = actions.values().stream().flatMap(List::stream)
    .max((action1, action2) -> Math.max(action1.getPriority(), action2.getPriority()));
  return result.isPresent() ? result.get().getPriority() : HConstants.PRIORITY_UNSET;
 }
}

代码示例来源:origin: goldmansachs/gs-collections

@Benchmark
public Position maxByMarketValue_serial_lazy_direct_methodref_jdk()
{
  return this.positions.getJdkPositions().stream().max(MARKET_VALUE_COMPARATOR_METHODREF).get();
}

代码示例来源:origin: prestodb/presto

@Override
  public Optional<QueryId> chooseQueryToKill(List<QueryMemoryInfo> runningQueries, List<MemoryInfo> nodes)
  {
    Map<QueryId, Long> memoryReservationOnBlockedNodes = new HashMap<>();
    for (MemoryInfo node : nodes) {
      MemoryPoolInfo generalPool = node.getPools().get(GENERAL_POOL);
      if (generalPool == null) {
        continue;
      }
      if (generalPool.getFreeBytes() + generalPool.getReservedRevocableBytes() > 0) {
        continue;
      }
      Map<QueryId, Long> queryMemoryReservations = generalPool.getQueryMemoryReservations();
      queryMemoryReservations.forEach((queryId, memoryReservation) -> {
        memoryReservationOnBlockedNodes.compute(queryId, (id, oldValue) -> oldValue == null ? memoryReservation : oldValue + memoryReservation);
      });
    }

    return memoryReservationOnBlockedNodes.entrySet().stream()
        .max(comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
  }
}

代码示例来源:origin: neo4j/neo4j

private long nextRelId( AbstractBaseRecord[] existingRecords )
  {
    return filterType( existingRecords, RelationshipRecord.class ).map(
        AbstractBaseRecord::getId ).max( Long::compareTo ).orElse( -1L ) + 1;
  }
}

代码示例来源:origin: graphhopper/graphhopper

private static Optional<List<Ticket>> ticketsBruteForce(Map<String, Fare> fares, Trip trip) {
  // Recursively enumerate all packages of tickets with which the trip can be done.
  // Take the cheapest.
  TicketPurchaseScoreCalculator ticketPurchaseScoreCalculator = new TicketPurchaseScoreCalculator();
  return allShoppingCarts(fares, trip)
      .max(Comparator.comparingDouble(ticketPurchaseScoreCalculator::calculateScore))
      .map(TicketPurchase::getTickets);
}

代码示例来源:origin: apache/hbase

/**
 * Gets the largest file (with reader) out of the list of files.
 * @param candidates The files to choose from.
 * @return The largest file; null if no file has a reader.
 */
static Optional<HStoreFile> getLargestFile(Collection<HStoreFile> candidates) {
 return candidates.stream().filter(f -> f.getReader() != null)
   .max((f1, f2) -> Long.compare(f1.getReader().length(), f2.getReader().length()));
}

相关文章