Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.filter()

Keeps only the stream elements that match a condition.

Available since: Java 8

Syntax

Stream<T> filter(Predicate<? super T> predicate)

Parameters

ParameterTypeDescription
predicatePredicate<? super T>A condition: an element stays if it is true.

Return value

Stream<T>A stream with only the matching elements.

Examples

Even numbers:

void main() {
    List<Integer> even = List.of(1, 2, 3, 4, 5, 6).stream()
        .filter(n -> n % 2 == 0)
        .toList();
    IO.println(even);
}

Output:

[2, 4, 6]

Several conditions in a row:

record Product(String name, double price, boolean inStock) {}
 
void main() {
    var products = List.of(
        new Product("mouse", 25, true),
        new Product("monitor", 199, true),
        new Product("cable", 5, false));
    products.stream()
        .filter(Product::inStock)
        .filter(p -> p.price() < 100)
        .forEach(p -> IO.println(p.name()));
}

Output:

mouse

Notes

The condition says what to keep (for removeIf() it says what to remove). The source collection does not change. To stop at the first non-matching element of an ordered stream, use takeWhile().

See also

  • Stream.map() — Transforms every element of a stream.
  • Collection.removeIf() — Removes all collection elements that match a condition.
  • Predicate — A condition: a function that takes a value and returns a `boolean`.
  • Stream.takeWhile() — Takes elements while a condition holds and stops at the first one that fails it.

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.