Java Stream findFirst()

The findFirst() method 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.

1. Stream findFirst() Method

Optional<T> findFirst()
  • The findAny() method is a terminal short-circuiting operation.
  • The findFirst() method returns an Optional.
  • The Optional contains the value as first element of the given stream, if 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 vaid 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. As soo as, we get the first element, the stream operation moves to ifPresent() method.

We print the first element in using the method reference inside ifPresent() method.

import java.util.stream.Stream;

public class Main 
{
	public static void main(String[] args) 
	{
		//sequential stream

		Stream.of("one", "two", "three", "four")
				.findFirst()
				.ifPresent(System.out::println);
		
		//parallel stream

		Stream.of("one", "two", "three", "four")
			.parallel()
			.findFirst()
			.ifPresent(System.out::println);
	}
}

Program output.

one
one

3. Stream 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 faster time. Else we can always use findFirst() in most of the cases.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial