Great question again, Stanley! 🔥
The filter()
method is one of the most commonly used tools in the Stream API, and it’s essential for writing clean, expressive code.
✅ What is the filter()
Method?
Stream<T> filter(Predicate<? super T> predicate)
📌 Purpose:
- To select only the elements that match a condition
- It uses a
Predicate<T>
(a function that returnstrue
orfalse
) - Returns a new stream with only the matching elements
🧠 Simple Example:
Stream<String> stream = Stream.of("apple", "banana", "avocado");
stream
.filter(s -> s.startsWith("a"))
.forEach(System.out::println);
// Output:
// apple
// avocado
✅ Key Characteristics
Feature | Description |
---|---|
💬 Functional | Accepts a lambda or method reference returning boolean |
🎯 Selective | Filters elements that satisfy a given condition |
💡 Lazy | It doesn’t run until a terminal operation is called |
🔁 Non-mutating | It does not modify the original source |
📌 Predicate Interface:
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
So you can pass any function like:
x -> x > 10
s -> s.contains("foo")
String::isEmpty
🔧 Practical Examples
✅ 1. Filter even numbers
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println); // Output: 2, 4
✅ 2. Filter non-null values
List<String> list = Arrays.asList("Java", null, "Streams");
list.stream()
.filter(Objects::nonNull)
.forEach(System.out::println); // Output: Java, Streams
🧠 Chaining filter()
with other operations
List<String> names = List.of("Anna", "Bob", "Alex", "John");
List<String> result = names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result); // Output: [ANNA, ALEX]
✅ Summary
Feature | filter() in Streams |
---|---|
📌 Purpose | Keeps elements that match a condition |
💡 Accepts | A Predicate<T> |
📤 Returns | A new Stream<T> with filtered elements |
🧠 Common usage | With .map() , .collect() , .forEach() |