How To Find The First Element Of An List Matching A Condition In Java 8 – Detailed Guide

The Java 8 Stream is a sequence of elements which supports sequential and parallel aggregate operations.
You can use the stream().filter(predicateFn).findFirst() method to find the first element based on the result of the predicate function(value -> value > 5).

In this tutorial, you will learn about finding the first element in a Java collection based on a condition.

Find first in a List of String

The Java 8 Predicate is a functional interface that returns a boolean value based on the specified condition.

To find the first element in a List of strings using the Java 8 Predicate function,

  • Iterate the list as a stream of elements using the .stream() method.
  • Invoke the stream().filter(predicateFn) with a predicate function to filter only the values matching the condition.
  • The Predicate function(value -> (value.startsWith("A"))) returns a boolean value either true/false. The only stream of value which satisfies the predicate condition and returns true are retained in the stream.
  • Use the .findFirst() method to return the first element in the new stream. The value will be returned as of type Optional, so the usefindFirst().get() method returns the first element.

Check this tutorial to return the default optional value, when no elements are found after applying the predicate condition, How To Achieve Functional Style of Java 8 Optional.ifPresent and Optional.else

    import java.util.Arrays;  
    import java.util.List;  
    import java.util.function.Predicate;

    //main
    List<String> names = Arrays.asList("Sam","Alex","Atman","Jessica","Ajmal","Priya");  
    Predicate<String> predicate = value -> (value.startsWith("A"));  
    String name = names.stream().filter(predicate).findFirst().get();  
    System.out.println(name);  //Alex

In the above example, The predicate function(value -> (value.startsWith("A"))) will filter the values("Alex","Atman","Ajmal") which start with a letter and create a new stream of elements. Using the .findFirst() on the new stream will return the first element based on the predicate function.

Find first in a List of Integer

To find the first element in a List of Integers using the Java 8 predicate function,

  • Iterate the List as a stream of elements using the .stream() method.
  • Use the stream().filter(predicateFn) method with a predicate function to filter the elements based on the condition(value -> (value > 7))
  • After filtering, return the first element using the .findFirst() method.
  • Use the .peek() method to identify the elements iterated until the first element is identified.
    import java.util.Arrays;  
    import java.util.List;  
    import java.util.function.Predicate;

    //main
    List<Integer> numbers = Arrays.asList(5,1,8,3,11,10);  
    Predicate<Integer> predicate = value -> (value > 7);  
    Integer firstNumber = numbers.stream().peek(item->System.out.println("visited value: "+item)).filter(predicate).findFirst().get();  
    System.out.println("FirstNumber: "+firstNumber);

Output

    visited value: 5
    visited value: 1
    visited value: 8
    FirstNumber: 8

The .filter() method is an intermediate operation which executes only when terminal operations(.findFirst()) are invoked. The findFirst() method selects first element in the stream that matches the condition.
The below examples demonstrate the behavior of parallel execution of a stream.

    List<Integer> numbers = Arrays.asList(5,1,8,3,11,10);  
    Predicate<Integer> predicate = x -> (x > 7);
    Integer firstNumber = numbers.stream().parallel().peek(item->System.out.println("visited value: "+item)).filter(predicate).findFirst().get();  
    System.out.println("FirstNumber: "+firstNumber);

Output

    visited value: 1
    visited value: 8
    visited value: 11
    visited value: 3
    visited value: 10
    visited value: 5
    FirstNumber: 8

If stream is not ordered, then any element may be returned method.

Find first in a List of Object

To find the first element in a list of an object based on the predication condition,

  • Iterate the object list as a stream of elements using the .stream() method.
  • Use the stream().filter(predicateFn) method with a predicate function to filter the Objects based on the condition.
  • Invoke the .findFirst() method to get the first element in the stream based on the predicate function result.
    //Student.java
    import lombok.AllArgsConstructor;  
    import lombok.Builder;  
    import lombok.Data;  

    @Data  
    @Builder  
    @AllArgsConstructor  
    public class Student {  
        String name;  
        long id;  
    }

    import com.techmam.model.Student;  
    import java.util.Arrays;  
    import java.util.List;  
    import java.util.function.Predicate;

    //main
    List<Student> students = Arrays.asList(new Student(null,100)  
                                          ,new Student("David",101)  
                                          ,new Student("Kumar",102)  
                                          ,new Student("Ameer",103));  
    Predicate<Student> predicate = value -> (value.getName()!=null);  
    Student student = students.stream().parallel().filter(predicate).findFirst().get();  
    System.out.println(student);  //Student(name=David, id=101)

In the above example, The predicate function(value -> (value.getName()!=null)) returns the non nullnames and the .findFirst() method returns the first object that satisfies the predicate function.

Related Topics

Leave a Comment