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

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

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

Stream.findAny介绍

[英]Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

This is a short-circuiting terminal operation.

The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use #findFirst() instead.)
[中]返回描述流的某个元素的可选值,如果流为空,则返回空可选值。
这是一个short-circuiting terminal operation
此操作的行为明显不确定;可以自由选择流中的任何元素。这是为了在并行操作中实现最大性能;代价是对同一个源的多次调用可能不会返回相同的结果。(如果需要稳定的结果,请改用#findFirst()

代码示例

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

@Override
 @Nullable
 public Long getLockId(String entryId, LockType lock)
 {
  return getLocks(entryId).entrySet().stream()
              .filter(entry -> entry.getValue().equals(lock))
              .map(Entry::getKey)
              .findAny()
              .orElse(null);
 }
}

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

public static boolean hasReferencesToScope(Node node, Analysis analysis, Scope scope)
{
  return getReferencesToScope(node, analysis, scope).findAny().isPresent();
}

代码示例来源:origin: thinkaurelius/titan

private static void verifyIncidentTraversal(FulgoraElementTraversal<Vertex,Edge> traversal) {
  //First step must be TitanVertexStep
  List<Step> steps = traversal.getSteps();
  Step<Vertex,?> startStep = steps.get(0);
  Preconditions.checkArgument(startStep instanceof TitanVertexStep &&
      TitanTraversalUtil.isEdgeReturnStep((TitanVertexStep) startStep),"Expected first step to be an edge step but found: %s",startStep);
  Optional<Step> violatingStep = steps.stream().filter(s -> !(s instanceof TitanVertexStep ||
      s instanceof OrderGlobalStep || s instanceof OrderLocalStep ||
          s instanceof IdentityStep || s instanceof FilterStep)).findAny();
  if (violatingStep.isPresent()) throw new IllegalArgumentException("Encountered unsupported step in incident traversal: " + violatingStep.get());
}

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

Partition partition = iterator.next();
 partitionDetailsMap.entrySet().stream()
     .filter(entry -> entry.getValue().fullSpec.equals(partition.getSpec()))
     .findAny().ifPresent(entry -> {
      entry.getValue().partition = partition;
      entry.getValue().hasOldPartition = true;
try {
 futures = executor.invokeAll(tasks);
 LOG.debug("Number of partitionsToAdd to be added is " + futures.size());
 for (Future<Partition> future : futures) {
  Partition partition = future.get();
     partitionDetailsMap.entrySet()
         .stream()
         .filter(entry -> !entry.getValue().hasOldPartition)
         .map(entry -> entry.getValue().partition)
         .collect(Collectors.toList()),
 throw e;
} finally {
 LOG.debug("Cancelling " + futures.size() + " dynamic loading tasks");
 executor.shutdownNow();

代码示例来源:origin: hs-web/hsweb-framework

/**
 * 根据id获取角色,角色不存在则返回null
 *
 * @param id 角色id
 * @return 角色信息
 */
default Optional<Role> getRole(String id) {
  if (null == id) {
    return Optional.empty();
  }
  return getRoles().stream()
      .filter(role -> role.getId().equals(id))
      .findAny();
}

代码示例来源:origin: Vedenin/useful-java-links

private static void testFindFirstSkipCount() {
  Collection<String> collection = Arrays.asList("a1", "a2", "a3", "a1");
  System.out.println("Test findFirst and skip start");
  // get first element of collection
  String first = collection.stream().findFirst().orElse("1");
  System.out.println("first = " + first); // print  first = a1
  // get last element of collection
  String last = collection.stream().skip(collection.size() - 1).findAny().orElse("1");
  System.out.println("last = " + last ); // print  last = a1
  // find element in collection
  String find = collection.stream().filter("a3"::equals).findFirst().get();
  System.out.println("find = " + find); // print  find = a3
  // find 3 element in collection
  String third = collection.stream().skip(2).findFirst().get();
  System.out.println("third = " + third); // print  third = a3
  System.out.println();
  System.out.println("Test collect start");
  // get all element according pattern
  List<String> select = collection.stream().filter((s) -> s.contains("1")).collect(Collectors.toList());
  System.out.println("select = " + select); // print  select = [a1, a1]
}

代码示例来源:origin: line/armeria

@BeforeClass
public static void init() throws Exception {
  server.start().get();
  httpPort = server.activePorts().values().stream()
           .filter(ServerPort::hasHttp).findAny().get()
           .localAddress().getPort();
  httpsPort = server.activePorts().values().stream()
           .filter(ServerPort::hasHttps).findAny().get()
           .localAddress().getPort();
}

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

private void closeWorker()
    throws Exception
{
  int nodeCount = getNodeCount();
  DistributedQueryRunner queryRunner = (DistributedQueryRunner) getQueryRunner();
  TestingPrestoServer worker = queryRunner.getServers().stream()
      .filter(server -> !server.isCoordinator())
      .findAny()
      .orElseThrow(() -> new IllegalStateException("No worker nodes"));
  worker.close();
  waitForNodes(nodeCount - 1);
}

代码示例来源:origin: hs-web/hsweb-framework

protected AccessTokenInfo getClientCredentialsToken() {
  return oAuth2UserTokenRepository
      .findByServerIdAndGrantType(serverConfig.getId(), GrantType.client_credentials)
      .stream()
      .findAny()
      .orElse(null);
}

代码示例来源:origin: stackoverflow.com

Stream<Integer> quickSort(List<Integer> ints) {
  // Using a stream to access the data, instead of the simpler ints.isEmpty()
  if (!ints.stream().findAny().isPresent()) {
    return Stream.of();
  }

  // treating the ints as a data collection, just like the C#
  final Integer pivot = ints.get(0);

  // Using streams to get the two partitions
  List<Integer> lt = ints.stream().filter(i -> i < pivot).collect(Collectors.toList());
  List<Integer> gt = ints.stream().filter(i -> i > pivot).collect(Collectors.toList());

  return Stream.concat(Stream.concat(quickSort(lt), Stream.of(pivot)),quickSort(gt));
}

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

@Test
void streamFilesRecursiveRenameMustCanonicaliseTargetFile() throws Exception
{
  // File 'b' should canonicalise from 'b/poke/..' to 'b', which is a file that doesn't exists.
  // Thus, this should not throw a NoSuchFileException for the 'poke' directory.
  File a = existingFile( "a" );
  File b = new File( new File( new File( path, "b" ), "poke" ), ".." );
  FileHandle handle = fsa.streamFilesRecursive( a ).findAny().get();
  handle.rename( b );
}

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

private static ReplicationSourceManager getManagerFromCluster() {
 // TestReplicationSourceManagerZkImpl won't start the mini hbase cluster.
 if (utility.getMiniHBaseCluster() == null) {
  return null;
 }
 return utility.getMiniHBaseCluster().getRegionServerThreads()
   .stream().map(JVMClusterUtil.RegionServerThread::getRegionServer)
   .findAny()
   .map(HRegionServer::getReplicationSourceService)
   .map(r -> (Replication)r)
   .map(Replication::getReplicationManager)
   .get();
}

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

/**
 * Locates the {@link Transform} that corresponds to the specified model
 * and uses it to generate a <code>String</code>. If no view is associated 
 * with the model type, an empty <code>Optional</code> will be returned.
 *
 * @param model  the model
 * @return       the generated text if any
 */
default Optional<String> on(Object model) {
  final Object m;
  
  if (model instanceof Optional) {
    final Optional<?> result = (Optional<?>) model;
    if (result.isPresent()) {
      m = result.get();
    } else {
      return Optional.empty();
    }
  } else {
    m = model;
  }
  
  return metaOn(m).map(Meta::getResult).findAny();
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * The simple broker produces {@code SimpMessageType.CONNECT_ACK} that's not STOMP
 * specific and needs to be turned into a STOMP CONNECTED frame.
 */
private StompHeaderAccessor convertConnectAcktoStompConnected(StompHeaderAccessor connectAckHeaders) {
  String name = StompHeaderAccessor.CONNECT_MESSAGE_HEADER;
  Message<?> message = (Message<?>) connectAckHeaders.getHeader(name);
  if (message == null) {
    throw new IllegalStateException("Original STOMP CONNECT not found in " + connectAckHeaders);
  }
  StompHeaderAccessor connectHeaders = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
  StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED);
  if (connectHeaders != null) {
    Set<String> acceptVersions = connectHeaders.getAcceptVersion();
    connectedHeaders.setVersion(
        Arrays.stream(SUPPORTED_VERSIONS)
            .filter(acceptVersions::contains)
            .findAny()
            .orElseThrow(() -> new IllegalArgumentException(
                "Unsupported STOMP version '" + acceptVersions + "'")));
  }
  long[] heartbeat = (long[]) connectAckHeaders.getHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER);
  if (heartbeat != null) {
    connectedHeaders.setHeartbeat(heartbeat[0], heartbeat[1]);
  }
  else {
    connectedHeaders.setHeartbeat(0, 0);
  }
  return connectedHeaders;
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
public Optional<GrokPattern> loadByName(String name) {
  return store.values().stream()
      .filter(pattern -> pattern.name().equals(name))
      .findAny();
}

代码示例来源:origin: spotify/helios

/**
 * Verifies that all entries in the Collection satisfy the predicate. If any do not, throw an
 * IllegalArgumentException with the specified message for the first invalid entry.
 */
@VisibleForTesting
protected static <T> List<T> validateArgument(List<T> list, Predicate<T> predicate,
                       Function<T, String> msgFn) {
 final Optional<T> firstInvalid = list.stream()
   .filter(predicate.negate())
   .findAny();
 if (firstInvalid.isPresent()) {
  throw new IllegalArgumentException(firstInvalid.map(msgFn).get());
 }
 return list;
}

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

@CheckForNull
public static Qualifier fromKey(String key) {
 return Arrays.stream(values())
  .filter(qualifier -> qualifier.key.equals(key))
  .findAny()
  .orElse(null);
}

代码示例来源:origin: hs-web/hsweb-framework

/**
 * 根据权限id获取权限信息,权限不存在则返回null
 *
 * @param id 权限id
 * @return 权限信息
 */
default Optional<Permission> getPermission(String id) {
  if (null == id) {
    return Optional.empty();
  }
  return getPermissions().stream()
      .filter(permission -> permission.getId().equals(id))
      .findAny();
}

代码示例来源:origin: line/armeria

@Before
public void init() throws Exception {
  httpPort = server.activePorts()
           .values()
           .stream()
           .filter(ServerPort::hasHttp)
           .findAny()
           .get()
           .localAddress()
           .getPort();
}

代码示例来源:origin: pentaho/pentaho-kettle

/**
 * Uses a trans variable called "engine" to determine which engine to use.
 */
private Predicate<PluginInterface> useThisEngine() {
 return plugin -> Arrays.stream( plugin.getIds() )
  .filter( id -> id.equals( ( transMeta.getVariable( "engine" ) ) ) )
  .findAny()
  .isPresent();
}

相关文章