Challenge: Even Squares

Lab Java Beginner 10 points

Read n whole numbers. Using a stream, keep only the even numbers, square them, and print the resulting list (with System.out.println on the list).

Input

First n, then n whole numbers.

Output

The list, e.g. [4, 16].

Example

Input

5
1 2 3 4 5

Output

[4, 16]
Sample input available Sample output available
Editor
Java

Hints

Read the numbers into a List<Integer> first.

.filter(x -> x % 2 == 0).map(x -> x * x)

Collectors.toList() packs the result into a list.

Solution explanation

The stream reads like a sentence: take the numbers, keep the even ones, square them, collect them.

Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<Integer> nums = new ArrayList<>();
        for (int i = 0; i < n; i++) nums.add(sc.nextInt());
        List<Integer> result = nums.stream()
                .filter(x -> x % 2 == 0)
                .map(x -> x * x)
                .collect(Collectors.toList());
        System.out.println(result);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD