Thursday, 30 June 2016

Stream findFirst() Example in Java 8

findFirst() example in Stream, Java 8

The findFirst() operation returns an object of type Optional (tutorial for Optional Class here) describing the
first element of this stream, or an empty Optional if the stream is empty.
If the stream has no encounter order,then any element may be returned.

Stream<String> items=Stream.of("findFirst","Example","Stream","Java8");
Optional<String> op = items.findFirst();
System.out.println(op);       // Optional[findFirst]
System.out.println(op.get()); // findFirst

In the case where the Stream is empty the findFirst() method returns a empty Optional object.

Stream<String> items=Stream.of();
Optional<String> op = items.findFirst();

System.out.println(op); // Optional.empty

To conclude use the findFirst() method in Java 8 to find the first element of any Java 8 Stream.
It returns a object of type Optional.
If the Stream is empty it will return an empty Optional object in the form Optional.empty.