Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Define a condition using a lambda expression or a Predicate.
  2. Apply filter() on the stream with this condition.
  3. 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.