dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 7, 2019

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Understanding the FindAny Method

Learn how to use the findAny method in java.util.Stream. This returns an Optional describing an element, or an empty Optional if Stream is empty.

Also, remember that the same stream cannot be operated upon with multiple methods after a complete iteration.

import java.util.Optional;
import java.util.stream.Stream;

public class StreamsFindAny 
{

   public static void main(String[] args) 

   {
      StreamsFindAny streamsFindAny = new StreamsFindAny();
      streamsFindAny.proceed();
   }

   public void proceed() 
   {
      Stream stream = Stream.of("1","5","10");

      Optional findAnyOutput = stream.findAny();
      System.out.println("FindAny output: " + findAnyOutput);

      //If you fail to reinitialize the stream again (as below), you will end up in an Exception case since the stream has already been operated in the previous lines.
      //Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
      stream = Stream.of("1","5","10");

      long streamCount = stream.count();
      System.out.println("Count of elements in stream: " + streamCount);
   }

}

/*

Expected output:

[root@mypc]# java StreamsFindAny
FindAny output: Optional[1]
Count of elements in stream: 3

*/
M S Sridhar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Thanks for your registration, follow us on our social networks to keep up-to-date