Please note that in below examples, in order to get a Stream Object from List, you can also use List#parallelStream() method, but use it only if the List implementation supports thread-safety and parallelism (for example CopyOnWriteArrayList).

From Java 8 onwards, you can use Java Stream API to filter elements from a Collection like List, and in this approach we are going use findFirst() method on Stream which returns the first occurrence of that element.

In order to follow below example, create a class called Person and declare two variables, name as String and age as integer.

public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "[name : " +name + " , age : "+age +"]"; } }

Let's write a program to find the first person from list whose age is greater than 30.

public static void findFirstMatch() { List<Person> persons = List.of( new Person("Person A", 29), new Person("Person B", 32), new Person("Person C", 45), new Person("Person D", 39) ); Optional<Person> firstMatch = persons.stream(). filter(person -> person.getAge() >30).findFirst(); if(firstMatch.isPresent()) { System.out.println("Person with match found : " + firstMatch.get()); } else { System.out.println("No match found"); } }
Explanation of above code:

When you run the above program, you will get the below output.

Person with match found : [name : Person B , age : 32]

This approach is same as above except that in place of findFirst(), we are going call findAny() and the main difference is that the behavior of this operation is explicitly non deterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

public static void findFirstMatch() { List<Person> persons = List.of( new Person("Person A", 29), new Person("Person B", 32), new Person("Person C", 45), new Person("Person D", 39) ); Optional<Person> firstMatch = persons.stream(). filter(person -> person.getAge() >30).findAny(); if(firstMatch.isPresent()) { System.out.println("Person with match found : " + firstMatch.get()); } else { System.out.println("No match found"); } }

When you run the above program, you will get the below output. Please note that the output may not be same in your case and may vary.

Person with match found : [name : Person B , age : 32]

Above example complete source code can be found here on Github

Similar Articles

  1. Filter and collect elements from a List using Java Stream API (from Java 8 onwards)
  2. How to remove elements from a List
  3. How to remove elements from a List while iterating
  4. How to loop through elements of List in different ways