Java 25 (LTS) reference · Stream API
Java Stream filter() Method
Keep only the elements that match a condition. Intermediate and lazy: nothing runs until a terminal operation.
Java 25 (LTS) Since Java 8
Syntax
stream.filter(predicate)
Parameters
| Parameter | Description |
|---|---|
predicatePredicate<T> |
A test that returns true to keep an element. |
Return value
A new Stream<T>.
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 12, 8, 130, 44);
System.out.println(nums.stream().filter(n -> n > 10).toList());
}
}
Output
[12, 130, 44]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
record User(String name, boolean active) {}
List<User> users = List.of(new User("Ana", true), new User("Ben", false));
System.out.println(users.stream().filter(User::active).map(User::name).toList());
}
}
Output
[Ana]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.map()· Transform each element with a function and return a stream of the results.stream.toList()· Collect a stream's elements into an unmodifiable List. Shorter than collect(Collectors.toList()).- Java Streams · tutorial