How does the filter() method work in Java 8?

filter() is an intermediate Stream operation that takes a Predicate and returns a new stream containing only the elements for which the predicate evaluates to true.

Key Points: • filter() accepts a Predicate<T>, a functional interface with a single test(T) method returning boolean. • It is a lazy, intermediate operation — nothing happens until a terminal operation like collect() or forEach() is invoked. • Elements for which the predicate returns false are excluded from the resulting stream entirely. • Multiple filter() calls can be chained to apply several conditions in sequence. • filter() does not modify the original collection; it only affects what flows through the stream pipeline.

Example: Given a list of numbers, numbers.stream().filter(n -> n % 2 == 0) produces a stream containing only the even numbers.

Code Example:

List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);

List<Integer> evens = nums.stream()
        .filter(n -> n % 2 == 0)
        .collect(Collectors.toList());

System.out.println(evens); // [2, 4, 6]

Interview Tip: A concise interview answer is:

"filter() takes a Predicate and returns a new stream that only contains the elements matching that predicate. It's lazy, so it doesn't do any work until a terminal operation runs, and it's commonly used to extract a subset of a collection based on a condition."