BudiBadu Logo

Filter and Square Even Numbers

Java Easy 11 views
Like21

This Java challenge is about transforming a list in a clean, modern style. In Filter and Square Even Numbers, you receive a list of integers and must return a new list containing only even numbers, each squared, while preserving encounter order. Odd values are removed, even negative values stay valid after squaring, and an all-odd input should return an empty list.

The expected implementation style is stream-based, using filtering and mapping in sequence, then collecting into a result list. The judge calls Solution.filterAndSquareEven(nums) and compares your returned list directly against expected values, so order and exact numeric output both matter. For example, 0 should remain 0, and -4 should become 16.

Focus on readable Java code: one clear pipeline, no side effects, and no mutation of input assumptions. The result must be deterministic for the same input and should not include any extra formatting, logging text, or wrapper objects, because the checker only evaluates the returned list content on every run.

Examples

Example 1
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output
[4, 16, 36, 64, 100]
Explanation

Filter even numbers (2, 4, 6, 8, 10) and square them using Streams.

Example 2
Input
[2, 4, 6, 8]
Output
[16, 64]
Explanation

Filter even numbers (2, 4, 6, 8) and square them using Streams.

Example 3
Input
[1, 3, 5, 7, 9]
Output
[]
Explanation

No even numbers, so return empty list.

Algorithm Flow

Recommendation Algorithm Flow for Filter and Square Even Numbers - Budibadu
Recommendation Algorithm Flow for Filter and Square Even Numbers - Budibadu

Best Answers

java - Approach 1
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());
    }
}