filter, map, collect

Lab Java Intermediate 20 points

Read n integers. Using a stream, keep the even ones, square them and collect into a List. Print the list and its sum.

Input

n, then n integers.

Output

Two lines.

Example

Input

6
1 2 3 4 5 6

Output

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

Hints

filter keeps matching items; map transforms each item.

Collectors.toList() gathers the result (Java 8 has no .toList()).

Solution explanation

A stream pipeline describes what to compute; nothing runs until the terminal operation (collect, sum, ...).

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> squares = nums.stream()
                .filter(x -> x % 2 == 0)
                .map(x -> x * x)
                .collect(Collectors.toList());
        System.out.println(squares);
        System.out.println(squares.stream().mapToInt(Integer::intValue).sum());
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD