Your first stream pipeline: filter, map and collect.
What to build
A program that squares the even numbers of a list.
Requirements
- Read a line of whole numbers. With a stream, print the squares of the even numbers in input order, separated by spaces (
noneif there are none), thensum: Sof those squares.
Input
One line of whole numbers separated by spaces.
Output
Two lines.
Constraints
At most 100 numbers, each with absolute value at most 10^4.
Example
Input:
1 2 3 4
Output:
4 16
sum: 20
Why it works
filter keeps only even numbers and map squares them, so the pipeline reads like the task itself, and mapToLong totals the same values.
Examples
Example 1 · Input
1 2 3 4
Expected output
4 16 sum: 20
Example 2 · Input
1 3 5
Expected output
none sum: 0
Hints
Hint 1
Arrays.stream(...) or a List of Integer, then filter(n -> n % 2 == 0) and map(n -> n * n).
Hint 2
Collectors.joining(" ") needs strings: map(String::valueOf) first.
Solution
Show one correct solution (try it yourself first)
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Long> squares = Arrays.stream(in.nextLine().trim().split(" "))
.map(Long::parseLong)
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
String text = squares.stream().map(String::valueOf).collect(Collectors.joining(" "));
System.out.println(squares.isEmpty() ? "none" : text);
System.out.println("sum: " + squares.stream().mapToLong(Long::longValue).sum());
}
}