Tabnine Logo
Stream.findAny
Code IndexAdd Tabnine to your IDE (free)

How to use
findAny
method
in
java.util.stream.Stream

Best Java code snippets using java.util.stream.Stream.findAny (Showing top 20 results out of 11,025)

Refine searchRefine arrow

  • Stream.filter
  • List.stream
  • Optional.isPresent
  • Optional.get
  • Optional.orElse
  • List.size
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();
}
java.util.streamStreamfindAny

Javadoc

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.)

Popular methods of Stream

  • collect
  • map
  • filter
  • forEach
  • findFirst
  • of
  • anyMatch
  • flatMap
  • sorted
  • toArray
  • count
  • allMatch
  • count,
  • allMatch,
  • concat,
  • reduce,
  • mapToInt,
  • distinct,
  • empty,
  • noneMatch,
  • iterator

Popular in Java

  • Finding current android device location
  • startActivity (Activity)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • BigInteger (java.math)
    An immutable arbitrary-precision signed integer.FAST CRYPTOGRAPHY This implementation is efficient f
  • SocketTimeoutException (java.net)
    This exception is thrown when a timeout expired on a socket read or accept operation.
  • DateFormat (java.text)
    Formats or parses dates and times.This class provides factories for obtaining instances configured f
  • StringTokenizer (java.util)
    Breaks a string into tokens; new code should probably use String#split.> // Legacy code: StringTo
  • Annotation (javassist.bytecode.annotation)
    The annotation structure.An instance of this class is returned bygetAnnotations() in AnnotationsAttr
  • Notification (javax.management)
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now