Java 8 Streams API – findAny, findFirst methods tutorial with examples

Introduction – This tutorial explains the Java 8 Stream API’s 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.

The below code shows how to use the 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());
    }
  }
}
 OUTPUT of the above code
Any Employee above age 40:  Employee Name:Tom Jones   Age:45
Explanation of the code

  • Employee class is defined with two attributes – name and age.
  • The FindInStreams class creates a static list of 8 Employee objects named employeeList.
  • In the main() method of the FindInStreams class the employeeList 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 of Optional class named – anyEmpAbove40.
  • The get() method of Optional is invoked on to get the Employee object in anyEmpAbove40 after checking for a value’s presence using Optional’s isPresent() method.
  • As seen in the output – Tom Jones with age 45 is the employee fetched using the findAny() 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 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().

Definition of 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());
  }
}
 OUTPUT of the above code
First employee below 30:  Employee Name:Harry Major   Age:25
Explanation of the code

  • The Stream of Employee 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 of Optional class named – firstEmpBelow30.
  • The get() method of Optional is invoked on firstEmpBelow30 to get the Employee object in it after checking for a value’s presence using Optional’s isPresent() method.
  • As seen in the output – Harry Major with age 25 is the employee fetched using the findFirst() method.

Summary
In this tutorial we understood the 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.

 

Digiprove sealCopyright © 2014-2016 JavaBrahman.com, all rights reserved.