Skip to content
On this page

Using filter

The Stream.filter() method is another common transformation method in Stream.

The filter() operation tests each element of a Stream, and elements that do not satisfy the condition are "filtered out," leaving only the elements that meet the criteria to form a new Stream.

For example, if we call filter() on a Stream of 1, 2, 3, 4, 5, with a test function f(x) = x % 2 != 0 to determine if the element is odd, it filters out the even numbers, leaving only the odd numbers, resulting in a new sequence 1, 3, 5:

    f(x) = x % 2 != 0


  ┌───┬───┬───┬───┼───┬───┬───┬───┐
  │   │   │   │   │   │   │   │   │
  ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼   ▼

[ 1   2   3   4   5   6   7   8   9 ]

  │   X   │   X   │   X   │   X   │
  ▼       ▼       ▼       ▼       ▼

[ 1       3       5       7       9 ]

The following code demonstrates this logic using IntStream:

java
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
                .filter(n -> n % 2 != 0)
                .forEach(System.out::println);
    }
}

As shown in the results, the Stream elements may be reduced after filter().

The filter() method accepts an object of the Predicate interface, which defines a test() method to determine if the element meets the criteria:

java
@FunctionalInterface
public interface Predicate<T> {
    // Determine if the element t meets the criteria:
    boolean test(T t);
}

Besides numbers, the filter() method can also be applied to any Java object. For instance, it can filter out weekdays from a given set of LocalDate to obtain only weekends:

java
import java.time.*;
import java.util.function.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Stream.generate(new LocalDateSupplier())
                .limit(31)
                .filter(ldt -> ldt.getDayOfWeek() == DayOfWeek.SATURDAY || ldt.getDayOfWeek() == DayOfWeek.SUNDAY)
                .forEach(System.out::println);
    }
}

class LocalDateSupplier implements Supplier<LocalDate> {
    LocalDate start = LocalDate.of(2020, 1, 1);
    int n = -1;
    public LocalDate get() {
        n++;
        return start.plusDays(n);
    }
}

Practice

Use filter() to filter out students who passed the exam and print their names.

Summary

The filter() method tests each element of a Stream, and elements that pass the test are filtered to generate a new Stream.

Using filter has loaded