Java 8 FAQ: Top Questions
14. How does the filter() method work in Java 8 Streams?
The filter()
method is an intermediate operation in the Stream API that evaluates each element against a provided Predicate
. Only elements that match the condition are retained in the resulting stream.
πΊοΈ Step-by-Step Instructions:
- Define a condition using a lambda expression or a Predicate.
- Apply
filter()
on the stream with this condition. - Only matching elements will proceed to the next operation in the stream pipeline.
π₯ Example Input:
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List even = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
π Expected Output:
[2, 4, 6]
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class StreamFilterExample {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List even = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(even);
}
}
π Detailed Explanation:
- filter(): Uses a Predicate to test each element.
- Lazy evaluation: Doesn't execute until a terminal operation like
collect()
is called. - Composable: Can be combined with
map()
,sorted()
, and others in a pipeline.
π οΈ Use Cases:
- Extracting elements that satisfy a business rule.
- Filtering out invalid or null values from a data stream.
- Dynamic query pipelines for APIs or search systems.