Member-only story
How to Filter a List of Person
Objects Based on Name
and Age
Using Java 8 Streams
1 min readSep 3, 2024
In Java 8, the introduction of Streams brought a powerful and expressive way to process collections of objects. This article will walk you through filtering a list of Person
objects based on certain criteria, such as name
and age
, and also demonstrate how to filter objects using two boolean conditions.
Filtering Based on Name
and Age
Let’s start by filtering a list of Person
objects to find those whose name
is "Raja" and whose age
is greater than 50.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class CollectionFilterExample {
public static void main(String[] args) {
List<Person> list = Arrays.asList(
new Person("Sanjay", 1, 20),
new Person("Mohan", 2, 30),
new Person("Mohan", 8, 60),
new Person("Raja", 14, 40),
new Person("Anu", 9, 70),
new Person("Raja", 15, 70)
);
Predicate<Person> filterName = person -> person.getName().equals("Raja");
Predicate<Person> filterAge = person -> person.getAge() > 50;
List<Person> filteredPersons = list.stream()
.filter(filterName.and(filterAge))
.collect(Collectors.toList());
filteredPersons.forEach(System.out::println);
}
}