Course contentsShow
← Java
Lesson 1641 of 2,87035. Functional InterfacesFree lesson

Using Predicates with Collection Filtering

Apply predicates in stream operations like filter() and removeIf() to select or exclude elements based on conditions.

Using Predicates with Collection Filtering

What you'll learn: How to apply Predicate functions to filter collections using stream operations like filter() and removeIf().

Now that you understand what predicates are and how to create them with lambdas, it's time to put them to work. Predicates shine when filtering collections—selecting elements that match certain conditions or removing elements that don't.

Using Predicates with filter()

The filter() method in streams accepts a Predicate and keeps only elements where test() returns true:

List<String> names = List.of("Alice", "Bob", "Charlie", "Amanda");

// Predicate: names starting with 'A'
Predicate<String> startsWithA = name -> name.startsWith("A");

List<String> filtered = names.stream()
    .filter(startsWithA)
    .collect(Collectors.toList());
// Result: ["Alice", "Amanda"]

You can also inline the predicate directly:

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

List<Integer> evens = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
// Result: [2, 4, 6]

Using Predicates with removeIf()

The removeIf() method works on mutable collections and removes all elements where the predicate returns true:

List<String> fruits = new ArrayList<>(List.of("apple", "banana", "apricot"));

Predicate<String> startsWithA = fruit -> fruit.startsWith("a");

fruits.removeIf(startsWithA);
// fruits is now ["banana"]

Think of It This Way

A predicate acts like a bouncer at a club. With filter(), you're building a new list of guests who pass the test. With removeIf(), you're physically escorting unwanted guests out of the existing list.

Key Takeaway: Predicates integrate seamlessly with collection operations—use filter() to create new filtered streams, and removeIf() to modify mutable collections in place by removing elements that match a condition.