The Java 8 Stream.findFirst() is a terminal operation that returns an Optional describing the first element of the given stream if stream is non-empty, or an empty Optional if the stream is empty.
The findFirst() is used to retrieve the first occurrence of an element that matches certain criteria, and when the order of elements is important.
1. Stream findFirst()
The method signature for findFirst()
is as follows:
Optional<T> findFirst();
- The
findAny()
method is a terminal short-circuiting operation. - The
findFirst()
method returns anOptional
. - The
Optional
contains the value as the first element of the given stream, if the stream is non-empty. - The
Optional
contains the empty value, if Stream is empty. - If the element selected is
null
, NullPointerException is thrown. - If Stream has defined encounter order, the findFirst() returns first element in encounter order.
- If Stream has no encounter order, the findFirst() may return any element.
- The above behavior is valid for all sequential and parallel streams. The behavior of findFirst() does not change by the parallelism of the Stream.
2. Stream findFirst() Example
In the given example, we are getting the first element from the Stream of strings. As soon as, we get the first element, the stream operation moves to Optional.ifPresent() method.
We print the first element using the method reference inside ifPresent() method.
Stream.of("one", "two", "three", "four")
.findFirst()
.ifPresent(System.out::println); // Prints 'one'
Similarly, we can use the findFirst() to get an element based on some condition. To apply the condition, we can use the filter() method.
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
Optional<String> firstWordStartingWithC = words.stream()
.filter(word -> word.startsWith("c"))
.findFirst();
firstWordStartingWithC.ifPresent(word ->
System.out.println("First word starting with 'c': " + word)); // Prints 'cherry'
Making the stream parallel does not change the behavior.
Stream.of("one", "two", "three", "four")
.parallel()
.findFirst()
.ifPresent(System.out::println); // Prints 'one'
3. Difference between findFirst() vs findAny()
In non-parallel streams, findFirst()
and findAny()
, both may return the first element of the Stream in most cases. But findAny()
does not offer any guarantee of this behavior.
Use findAny()
to get any element from any parallel stream in a faster time. Else we can always use findFirst()
in most cases.
Happy Learning !!
Comments