Java 8 Streams API - findAny, findFirst methods tutorial with examples
Introduction
This tutorial explains the Java 8 Stream API's
It is important to note that
Also, the
Where,
-
- returns an
The below code shows how to use the
OUTPUT of the above code
Explanation of the code
Definition of
Where,
-
- returns an
The below code shows how to use the
Note - Employee class and the static Employee list is the same as above example and hence has not been shown again for brevity.
OUTPUT of the above code
Explanation of the code
Summary
In this tutorial we understood the
findAny()
and findFirst()
methods with examples to show their usage. The tutorial assumes that you are familiar with basics of Java 8 Streams APIRead Basics of Java 8 Streams API.
Stream.findAny()
method
There are instances when the business specification says that any element of the stream satisfying a given criteria is to be fetched. I.e. an exact element match is not needed but any element from the satisfying set can be picked up. In such cases findAny()
method is an ideal fit because once you filter the streamTutorial on filtering in Java 8 Streams down to elements satisfying a particular criteria, then any element from the filtered stream can be picked up.It is important to note that
Stream.findAny()
method can literally give you any element from the stream on which it is called. I.e. you should not code with an expectation that a particular value will always be returned. This non-deterministic nature of the findAny()
method is very useful when executing parallel operations on a stream as it helps in performance optimisation without worrying about which element will be returned.Also, the
Stream.findAny()
method is a short-circuitingArticle explaining concepts of Short-Circuits in Computing and terminalClick to Read Tutorial explaining intermediate & terminal Stream operations operation.
Definition of Stream.findAny()
Method
The Stream.findAny()
method has the following signature - Optional<T> findAny()
Where,
-
findAny()
method does not take any input.- returns an
Optional
instance of type T where T is the type of the Stream on which this method is invoked.Stream.findAny()
method in your code.Java 8 code showing Stream.findFirst() method usage
package com.javabrahman.java8;
public class Employee{
private String name;
private Integer age;
public Employee(String name, Integer age){
this.name=name;
this.age=age;
}
//getters and setters for name and age attributes go here
//overridden equals() and hashcode() go here
public String toString(){
return "Employee Name:"+this.name
+" Age:"+this.age;
}
}
//FindInStreams.java
package com.javabrahman.java8.streams;
import com.javabrahman.java8.Employee;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class FindInStreams {
static List<Employee> employeeList = Arrays.asList(
new Employee("Tom Jones", 45),
new Employee("Harry Major", 25),
new Employee("Ethan Hardy", 65),
new Employee("Nancy Smith", 22),
new Employee("Deborah Sprightly", 29),
new Employee("Billy Kid", 22),
new Employee("George King",44),
new Employee("Annie Barrey", 19));
public static void main(String[] args) {
Optional<Employee> anyEmpAbove40 = employeeList.stream()
.filter(emp -> emp.getAge() > 40)
.findAny();
if(anyEmpAbove40.isPresent()){
System.out.println("Any Employee above age 40: " + anyEmpAbove40.get());
}
}
}
Any Employee above age 40: Employee Name:Tom Jones Age:45
Employee
class is defined with two attributes -name
andage
.- The
FindInStreams
class creates a static list of 8Employee
objects namedemployeeList
. - In the
main()
method of theFindInStreams
class theemployeeList
is converted to a stream and filtered such that it contains only employees with age > 40. - On the filtered stream
findAny()
method is invoked which returns an instance ofOptional
class named -anyEmpAbove40
. - The
get()
method ofOptional
is invoked on to get theEmployee
object inanyEmpAbove40
after checking for a value's presence usingOptional
’sisPresent()
method. - As seen in the output -
Tom Jones
with age45
is the employee fetched using thefindAny()
method.
Stream.findFirst()
method
There are cases where the business specification requires the first element of a filtered stream to be fetched. This method is useful when the stream being worked on has a defined encounter order. In such cases getting the first element becomes a simple method call using the Stream.findFirst()
method. This method is a short-circuiting terminal operation.
What is encounter order in Streams
Encounter order simply refers to the order in which the elements of a stream are processed. A stream made from an ordered source such as a
List
will have the encounter order defined as per the ordering of the elements in the source List
. On the other hand, a stream made from a source which does not have an intrinsic order of elements defined, such as a HashSet
, will not have any specific encounter order defined. Also, even if the initial stream's elements are unordered, an encounter order can be introduced using Stream
methods such as sorted()
.
Stream.findFirst()
Method
The Stream.findAny()
method has the following signature - Optional<T> findFirst()
Where,
-
findFirst()
method does not take any input.- returns an
Optional
instance of type T where T is the type of the Stream on which this method is invoked.The below code shows how to use the
Stream.findFirst()
method in your code.Note - Employee class and the static Employee list is the same as above example and hence has not been shown again for brevity.
Java 8 code showing Stream.findFirst() method usage
public static void main(String[] args) {
Optional<Employee> firstEmpBelow30 = employeeList.stream()
.filter(emp -> emp.getAge() < 30)
.findFirst();
if (firstEmpBelow30.isPresent()) {
System.out.println("First employee below 30: " + firstEmpBelow30.get());
}
}
First employee below 30: Employee Name:Harry Major Age:25
- The
Stream
ofEmployee
objects is filtered such that it contains only employees of age < 30. - The
findFirst()
method is invoked which returns the first element of the filtered stream as per the encounter order, or original list order, as an instance ofOptional
class named -firstEmpBelow30
. - The
get()
method ofOptional
is invoked onfirstEmpBelow30
to get theEmployee
object in it after checking for a value's presence usingOptional
’sisPresent()
method. - As seen in the output -
Harry Major
with age25
is the employee fetched using thefindFirst()
method.
Stream.findAny()
and Stream.findFirst()
methods of the Java 8 Streams API and saw code examples of their usage. We also understood the concept of encounter order in Streams.Java 8 Streams API tutorials on JavaBrahman
Streams API - Introduction & BasicsClick to Read tutorial on Streams API Basics Understanding Stream Operations | Intermediate and Terminal OperationsClick to Read Tutorial on Stream Operations Overview Mapping with Streams using map and flatMap methodsClick to Read how Mapping with Java8 Streams works Filtering and Slicing with Streams using filter,distinct,limit,skip methodsClick to Read how Filtering and Slicing with Java8 Streams works Matching with Streams using allMatch,anyMatch,noneMatch methodsClick to Read tutorial on matching with Streams API Stream API's findFirst,findAny methods' tutorialClick to Read tutorial on findFirst() and findAny() methods of Streams API 'Peeking' into a running Stream with Stream.peek() methodClick to Read tutorial on Stream.peek() method Creating Infinite Streams with iterate\generate methodsClick to Read tutorial on Creating Infinite Streams Reducing Streams using Streams.reduce methodClick to Read tutorial on Reducing Streams
Streams API - Introduction & BasicsClick to Read tutorial on Streams API Basics Understanding Stream Operations | Intermediate and Terminal OperationsClick to Read Tutorial on Stream Operations Overview Mapping with Streams using map and flatMap methodsClick to Read how Mapping with Java8 Streams works Filtering and Slicing with Streams using filter,distinct,limit,skip methodsClick to Read how Filtering and Slicing with Java8 Streams works Matching with Streams using allMatch,anyMatch,noneMatch methodsClick to Read tutorial on matching with Streams API Stream API's findFirst,findAny methods' tutorialClick to Read tutorial on findFirst() and findAny() methods of Streams API 'Peeking' into a running Stream with Stream.peek() methodClick to Read tutorial on Stream.peek() method Creating Infinite Streams with iterate\generate methodsClick to Read tutorial on Creating Infinite Streams Reducing Streams using Streams.reduce methodClick to Read tutorial on Reducing Streams