Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) 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.
Optional<T> findFirst() Where, Optional is a container object which may or may not contain a non-null value and T is the type of objects and the function returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.
Exception : If the element selected is null, NullPointerException is thrown.
Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns first element satisfying the intermediate operations.
Example 1 : findFirst() function on Stream of Integers.
Example 2 : findFirst() function on Stream of Strings.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.