Finding Operations in Stream

This lesson discusses the finding operations in Streams provided by the findFirst() and findAny() methods.

We'll cover the following

In the previous lesson, we looked at matching operations. Those operations check whether the elements in the stream match particular criteria, and they return true or false.

However, sometimes we need to get the matched element instead of just verifying if it is present or not. The finding operations are used for this purpose. There are two basic finding operations in streams, i.e., findFirst() and findAny().

These operations are typically used with a filter() operation, but it is not necessary that they are used only with a filter() operation.

Let’s discuss each finding operation.

1) findFirst()

Below is the syntax of this operation.

Optional<T> findFirst()

It returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. We already discussed Optional in our lambda expression chapter. Please revisit that lesson to learn about Optional.

In the below example we have a list of Person objects. We need to get the first person on the list who belongs to a particular country.

Get hands-on with 1400+ tech skills courses.