CodeBlanks Logo Icon CodeBlanks

filter

Learn to filter elements with filter.

Filtering with filter

filter(Predicate) is an intermediate operation that keeps elements matching a condition in a new stream. Predicate<T> is a functional interface with a single test(T) method that returns boolean.

Example: names.stream().filter(s -> s.length() > 3) keeps names longer than three. filter is lazy, so it does nothing on its own; a terminal operation must follow. You can also chain multiple filter calls.

What is a Predicate?

Predicate<T> is a condition function; its test(T) method returns boolean. s -> s.isEmpty() is a Predicate lambda. filter calls the Predicate for each element; if it returns true the element is kept.

You can combine multiple conditions with &&: s -> s.length() > 3 && s.startsWith("A"). Or chain two filter calls; the result is the same. For composite conditions you can also use combiners like Predicate.and.

Practice Count long names

Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alexander", "Alex". Count names longer than five with long count = names.stream().filter(s -> s.length() > 5).count();. Print it with System.out.println(count);.

Starter code

Main.java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Declare List<String>, add 3 names, count names longer than 5, print

    }
}

Sample solution

Main.java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ayşe");
        names.add("Alexander");
        names.add("Alex");
        long count = names.stream().filter(s -> s.length() > 5).count();
        System.out.println(count);
    }
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the filter call

Question
names.stream().____(s -> s.length() > 3)
Answer
names.stream().filter(s -> s.length() > 3)

Explanation: The filter method expects a Predicate.

2 Which functional interface does filter expect?

  • Predicate Correct answer
  • Consumer
  • Supplier
  • Runnable

Explanation: filter expects a Predicate<T>; the test(T) method returns boolean.

3 Match the filter concepts

Term Meaning
filter(...) Keeps matches
Predicate<T> Condition function
test(T) Returns boolean
s -> s.length() > 3 Lambda Predicate

All lessons in Intermediate