BudiBadu Logo

Filter and Square Even Numbers

Java Easy 8 views

Practice using the Java Streams API to process collections in a clear, declarative style. You will work with a list of integers and apply stream operations such as filtering, mapping, and collecting to produce a transformed result instead of writing traditional loops.

The task is to design a stream-based solution that reads an input list, applies the required conditions, and returns the correct final list while keeping the code readable and efficient. Focus on choosing the right sequence of intermediate operations and a suitable terminal operation so that the behavior is easy to understand and extend.

Example 1:

Input: numbers = [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.

Example 2:

Input: numbers = [2, 4, 6, 8]
Output: [16, 64]
Explanation: Filter even numbers, square them, keep only values greater than 10.

Example 3:

Input: numbers = [1, 3, 5, 7, 9]
Output: []
Explanation: No even numbers found, 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());
    }
}