java · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
limit first, sorted second. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> times = List.of(58, 41, 63, 39, 47);
System.out.println(times.stream()
.limit(3)
.sorted()
.collect(Collectors.toList()));
}
}
your turn
Your turn. Gather every tag.
Each post holds a list of tags. On line 10, use flatMap to pour every post's tags into one stream. A list's stream() method gives a stream of its items.
output
press run to see what happens
fix it
The queue counts once, then crashes. Can you fix it?
output
press run to see what happens
- The count works, then line 9 throws
IllegalStateException. What happened topeopleon line 8? countis a terminal operation, so the stream inpeopleis spent after line 8.- Use a fresh stream each time: write
queue.stream()in place ofpeopleon lines 8 and 9, then run.
nailed it
you can sort, slice and flatten streams. :D
sorted,distinctandlimitrun in the order you write them.flatMappours nested values into one flat stream.- A stream is used once. Call
stream()again for more.
new words in your collection
- distinct
- limit
- flatMap
This lesson isn’t saved. A free account remembers every lesson you finish.