Filter Even Numbers Using Streams in Java
Problem
A stream is a pipeline over a collection's elements; filter is an intermediate operation that passes along only the elements matching a condition.
Given a list of integers, build a new list containing only the even numbers, leaving the original list unchanged.
Java Program
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(14, 3, 8, 21, 6, 17, 10);
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0) // keep only the values that pass the test
.collect(Collectors.toList());
System.out.println("All numbers: " + numbers);
System.out.println("Even numbers: " + evens);
}
}Output
Core Logic
A stream pipeline reads like a description of the result: take the numbers, keep the even ones, collect them into a list.
- 1
numbers.stream()opens a stream over the list without modifying it. - 2
filter(n -> n % 2 == 0)passes along only values whose remainder by 2 is zero. - 3
collect(Collectors.toList())is the terminal operation that runs the pipeline and gathers the results. - 4Printing both lists shows the original is untouched.
Key Point: Nothing happens until a terminal operation such as collect runs — intermediate steps like filter are lazy and only describe the work.
Why: Every element is tested once, and the new list holds the k elements that passed.
Key Concepts
Approach 2: Without Streams (for-each Loop)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FilterEvenNumbersLoop {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(14, 3, 8, 21, 6, 17, 10);
List<Integer> evens = new ArrayList<>();
for (int n : numbers) {
if (n % 2 == 0) {
evens.add(n); // the same test, written as an if inside a loop
}
}
System.out.println("Even numbers: " + evens);
}
}
Output
Core Logic
The same filter written the pre-Java 8 way makes it clear what the stream version does for you.
- 1An empty
ArrayListis created to hold the results. - 2A for-each loop visits every number.
- 3An
ifapplies the samen % 2 == 0test and adds passing values.
[14, 8, 6, 10].Key Point: Both versions do identical work; streams win on readability when several steps are chained, such as filter then map then sort.
Why: One pass over n elements, with k of them copied into the result.
Key Concepts
Interview Questions
Can a stream be reused after collect()?
No. A stream can be consumed only once; calling another terminal operation throws IllegalStateException. Create a new stream from the source instead.
What's the difference between filter and map?
filter decides which elements continue, without changing them. map transforms every element into something else.