How to Use Stream Filter in Java: Simple Guide with Examples
In Java, you use
stream().filter() to select elements from a collection that match a condition. The filter method takes a condition as a lambda expression and returns a new stream with only the elements that satisfy that condition.Syntax
The filter method is used on a stream and takes a Predicate (a condition) as an argument. It returns a new stream containing only elements that pass the condition.
stream(): Converts a collection into a stream.filter(condition): Keeps elements whereconditionis true.collect(): Gathers the filtered elements back into a collection.
java
collection.stream()
.filter(element -> condition)
.collect(Collectors.toList());Example
This example shows how to filter a list of numbers to keep only even numbers using stream().filter().
java
import java.util.*; import java.util.stream.*; public class StreamFilterExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); } }
Output
[2, 4, 6]
Common Pitfalls
One common mistake is forgetting to collect the filtered stream back into a collection, which means no output is produced. Another is using a filter condition that always returns true or false, which defeats the purpose.
Also, streams are lazy; without a terminal operation like collect() or forEach(), the filter won't run.
java
import java.util.*; import java.util.stream.*; public class FilterPitfall { public static void main(String[] args) { List<String> names = Arrays.asList("Anna", "Bob", "Alice"); // Wrong: No terminal operation, so nothing happens names.stream() .filter(name -> name.startsWith("A")); // Right: Collect results to a list List<String> filtered = names.stream() .filter(name -> name.startsWith("A")) .collect(Collectors.toList()); System.out.println(filtered); } }
Output
[Anna, Alice]
Quick Reference
Remember these tips when using stream().filter():
- Always use a terminal operation like
collect()orforEach()to execute the stream. - The filter condition is a lambda that returns
truefor elements to keep. - Streams do not change the original collection.
- Filter can be chained with other stream operations like
map()orsorted().
Key Takeaways
Use
stream().filter() to select elements matching a condition from a collection.Always end the stream with a terminal operation like
collect() to get results.The filter condition is a lambda expression returning true for elements to keep.
Streams do not modify the original collection; they create new filtered streams.
Common mistakes include missing terminal operations and incorrect filter conditions.