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

11.5 Stream pipelines — transforming with map

Lesson

Превратить каждый элемент в другой

mapToInt turned elements into numbers to add them up. The general version is map: it applies a lambda to every element and passes on the results, whatever their type.


Worked example

List<String> words = List.of("pear", "fig", "apple");

words.stream().map(w -> w.toUpperCase()).collect(Collectors.toList());
// [PEAR, FIG, APPLE]

With records this gets genuinely useful: filter the objects you want, then map them to the field you need.

students.stream()
        .filter(s -> s.score() >= 70)
        .map(s -> s.name())
        .collect(Collectors.toList());   // [Ada, Bo]

Read it aloud: take the students, keep those scoring 70 or more, take their names, collect them. Three lines that would have been a loop, a condition and an accumulator.


▶ Try it: run this, then change something and run it again.



map does what?


In the pipeline filter(...).map(...), which runs first?


Type exactly what this program prints.

import java.util.List;
import java.util.stream.Collectors;

public class Main { public static void main(String[] a){
    List<String> w = List.of("ab", "cde", "f");
    System.out.println(w.stream().map(s -> s.length()).collect(Collectors.toList()));
}}

Why do records work well with streams?


True or false?