filter() is an intermediate Stream operation that keeps only the elements matching a given predicate, letting you build a new stream containing just the even numbers from a list.
Key Points: • filter(predicate) evaluates the predicate for each element and passes through only those returning true. • The predicate here, n -> n % 2 == 0, checks whether a number is evenly divisible by two. • filter() is lazy - it doesn't run until a terminal operation like collect() or forEach() triggers the pipeline. • collect(Collectors.toList()) gathers the filtered elements into a concrete List for further use. • Multiple filter() calls can be chained to apply several conditions in sequence, equivalent to combining predicates with &&.
Example: Given the list [1, 2, 3, 4, 5, 6], filtering with n -> n % 2 == 0 produces a new list containing just [2, 4, 6].
Code Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());Interview Tip: A concise interview answer is:
"I use filter(n -> n % 2 == 0) to keep only elements where the modulo-two check passes, then collect the results into a new list with Collectors.toList(). filter() is lazy, so nothing actually runs until a terminal operation like collect() triggers the pipeline."