Filter and Square Even Numbers
You are given a list of integers and need to build a new list from it in two steps.
First keep only the even numbers. After that, square each remaining value. The order should stay the same as the original list after filtering. So if an even number appears earlier than another even number, its squared result should also appear earlier in the answer.
For example, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] becomes [4, 16, 36, 64, 100] because the even values are 2, 4, 6, 8, 10 and their squares are collected in that same left-to-right order. If the input is [1, 3, 5, 7, 9], the answer is an empty list because no value passes the even-number filter.
So the task is to filter the list by parity and then transform the kept values into their squares.
Example Input & Output
Filter even numbers (2, 4, 6, 8, 10) and square them using Streams.
Keep all the even numbers and square each one in the same left-to-right order.
No even numbers, so return empty list.
Algorithm Flow

Solution Approach
This problem is a good fit for the Java Streams pipeline style because the work naturally happens in stages. We are not mutating the original list one element at a time by hand. Instead, we want a clear pipeline that says: start from the input list, keep only the values that pass a condition, transform them, then collect the result.
The first stage is filtering. An even number satisfies n % 2 == 0, so the stream should keep only those values. The second stage is mapping. Once a value has passed the filter, convert it to n * n. Finally, collect the transformed values into a new list.
In Java, that idea looks like this:
numbers.stream().filter(n -> n % 2 == 0).map(n -> n * n).collect(Collectors.toList())
This works well because each step has one job. filter removes the odd numbers, map squares what remains, and collect builds the final list. The result preserves encounter order, which is exactly what the examples expect. The full solution runs in O(n) time, and the extra space is proportional to the size of the output list.
Best Answers
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public static List<Integer> filterAndSquareEven(List<Integer> numbers) {
if (numbers == null) {
return List.of();
}
return numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
