Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.4 Lambdas and streams — transforming and summing

Lesson

Turning elements into numbers and adding them

To add up values, turn the stream into a stream of ints with mapToInt(lambda), then call sum(). The lambda transforms each element; sum() adds the results. This one line replaces a loop with an accumulator.


Worked example

List<Integer> nums = List.of(1, 2, 3, 4);

int total = nums.stream().mapToInt(n -> n).sum();        // 10
int sumSquares = nums.stream().mapToInt(n -> n * n).sum();// 1+4+9+16 = 30

System.out.println(total);
System.out.println(sumSquares);

mapToInt(n -> n) just passes the values through; mapToInt(n -> n * n) squares them first.


▶ Try it: run this — a plain sum and a sum of squares, each in one line.



mapToInt(lambda) is used to...


After mapToInt, calling sum() gives...


Type exactly what this program prints.

import java.util.List;
public class Main { public static void main(String[] a){
    List<Integer> xs = List.of(2, 3, 4);
    System.out.println(xs.stream().mapToInt(n -> n * 10).sum());
}}

The stream pipeline mapToInt(n -> n * n).sum() replaces...


Match each stream operation to what it does.


True or false?