×

java · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

turns a stream of lines into a stream of words.

sorted() puts items in their natural order, or pass a comparator: sorted(Comparator.reverseOrder()). drops repeats. lets only the first three through, and skip(3) jumps past them. Together they make a top-three list in one pipeline.

Sometimes each item holds many values, like a line holding words. map would give a stream of arrays. flatMap opens each one up and pours the contents into a single stream: flatMap(line -> Arrays.stream(line.split(" "))).

A stream can be used once. After its terminal operation it is spent, and touching it again throws IllegalStateException. Need the data twice? Call stream() again.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
    public static void main(String[] args) {
        List<String> lines = List.of("the cat sat", "on the mat", "the end");
        List<String> words = lines.stream()
            .flatMap(line -> Arrays.stream(line.split(" ")))
            .distinct()
            .sorted()
            .collect(Collectors.toList());
        System.out.println(words);
        List<Integer> top = List.of(40, 95, 70, 95, 12).stream()
            .sorted(Comparator.reverseOrder())
            .limit(3)
            .collect(Collectors.toList());
        System.out.println(top);
    }
}

Arrays.stream(array) opens a stream over an array, the way stream() does for a list.