Tuesday, March 27, 2018

Java 8 Stream findFirst() and findAny() methods with Example

In this post you will learn finding elements in a stream based on predicate condition with the help of Stream.findFirst() and Stream.findAny() methods. Let us discuss one by one

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 stream 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 optimization without worrying about which element will be returned.

Both findFirst() and findAny() are short-circuit method, much like short circuit AND (&&) and OR (||) operator which will not evaluate anymore element once they found one.

Stream.findAny() method returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

Optional<T> java.util.stream.Stream.findAny();


In the above statement ,
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 following example shows how to use Stream.findAny() method

Student POJO
package com.byluckysir.java8;
public class Student{
  private String name;
  private Integer age;
  public Student(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 "Student Name:"+this.name
      +"  Age:"+this.age;
  }
}

//FindInStrems.java
package com.byluckysir.java8.streams;
import com.byluckysir.java8.Student;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class FindInStreams {
  static List<Student> studentList = Arrays.asList(
    new Student("pavan", 19),
    new Student("Ramesh", 25),
    new Student("eeswar", 23),
    new Student("lakshmi", 22),
    new Student("maneesha", 21),
    new Student("rohitha", 22),
    new Student("bharat",24),
    new Student("chandana", 19));
  public static void main(String[] args) {
    Optional<Student> anyStdAbove23 = StudentList.stream()
                                       .filter(std -> std.getAge() > 23)
                                       .findAny();
    if(anyStdAbove23.isPresent()){
      System.out.println("Any Student above age 23: " + anyStdAbove23.get());
    }
  }
}

Output:
Any Student above age 23:Student Name: bharat Age:24

Stream.findFirst():

Stream.findFirst() method returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.
Optional<T> java.util.stream.Stream.findFirst();



Student class and the static Student list is the same as above example

public static void main(String[] args) {
  Optional<Student> firstEmpBelow30 = StudentList.stream()
                                      .filter(std -> std.getAge() < 20)
                                      .findFirst();
  if (firstStdBelow20.isPresent()) {
    System.out.println("First Student below 20: " + firstStdBelow20.get());
  }
}

OUTPUT:
First Student below age 20:Student Name: pavan  Age:19


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...