Task 1 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 — sorted, distinct, collect

Lesson

Собрать результат, а не просто посчитать

So far streams ended in count() or sum() — a single number. But often you want a list back. That is what collect(Collectors.toList()) does: it gathers everything left in the pipeline into a new list.

Two more operations do the work in the middle: distinct() drops repeats, sorted() puts things in order.


Worked example

List<Integer> nums = List.of(5, 3, 5, 9, 1, 3);

nums.stream().distinct().count();                          // 4
nums.stream().sorted().collect(Collectors.toList());       // [1, 3, 3, 5, 5, 9]
nums.stream().distinct().sorted().collect(Collectors.toList()); // [1, 3, 5, 9]

Operations chain in the order you write them, and each one passes what is left to the next. The last call decides the shape of the answer: a number from count, a list from collect.

Note what the last line replaces: a TreeSet, a loop and a conversion — in one readable line.


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



collect(Collectors.toList()) returns...


distinct()...


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<Integer> l = List.of(4, 2, 4, 1);
    System.out.println(l.stream().distinct().sorted().collect(Collectors.toList()));
    System.out.println(l.stream().distinct().count());
}}

What decides whether you get a number or a list?


True or false?