How do I filter a list using a stream in Java?

You can use the Stream API’s filter() method to select elements that match a condition.

In this example, you will select numbers greater than or equal to 20 from a list and collect them into a new list.

Source code

Save the following code as FilterListExample.java:

import java.util.List;

public class FilterListExample {
    void main() {
        List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

        List<Integer> filteredNumbers = numbers.stream()
                .filter(number -> number >= 20)
                .toList();

        IO.println("Original list: " + numbers);
        IO.println("Filtered list: " + filteredNumbers);
    }
}

Explanation

The original list contains six integers:

List<Integer> numbers = List.of(5, 20, 12, 35, 8, 40);

The following pipeline selects the matching values and collects them:

List<Integer> filteredNumbers = numbers.stream()
        .filter(number -> number >= 20)
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
filter(...) Keeps elements that match the condition
toList() Collects the selected elements into a list

Defining the condition

The filter() method accepts a predicate: a function that checks an element and returns true or false.

Here, the predicate is a lambda expression:

number -> number >= 20

When the result is true, the number remains in the stream. When it is false, the number is excluded.

For this input, the matching values are 20, 35, and 40.

Collecting the result

filter() is an intermediate operation. It describes the selection but does not process the elements until a terminal operation runs.

In this example, toList() is the terminal operation:

.toList()

It collects the matching elements into an unmodifiable list. Calling add() or remove() on that result would throw an UnsupportedOperationException.

The result preserves the original list’s encounter order. Filtering does not change the original list.

Run the example

Compile and run the file:

javac FilterListExample.java
java FilterListExample

Output

Original list: [5, 20, 12, 35, 8, 40]
Filtered list: [20, 35, 40]

Combining conditions

Use && to require multiple conditions. For example, this filter keeps numbers that are at least 20 and even:

.filter(number -> number >= 20 && number % 2 == 0)

With the same input, the resulting list is:

[20, 40]

If no elements match the condition, toList() returns an empty list.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.