Member-only story

How to Filter a List of Person Objects Based on Name and Age Using Java 8 Streams

Sanjay Singh
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.

Java 8 Stream API [Solutions]

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);
}
}

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet