java · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A describes the result, not the loop.
Loops say how: make a list, go round, check, add. A stream says what. orders.stream() opens a stream of the items, filter keeps the ones you want, map changes each one, and collect(Collectors.toList()) gathers the results into a new list.
That chain is a pipeline. filter and map are intermediate operations: they set up work but do nothing yet. Only the at the end pulls items through. Without one, nothing runs at all.
The source list is never changed. A pipeline reads it and builds something new, which keeps the original safe for whoever uses it next.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> orders = List.of("latte", "tea", "flat white", "mocha", "tea");
List<String> labels = orders.stream()
.filter(drink -> !drink.equals("tea"))
.map(drink -> drink.toUpperCase())
.collect(Collectors.toList());
System.out.println(labels);
System.out.println(orders);
}
} Put each step on its own line, starting with a dot, so the pipeline reads top to bottom like a recipe.
guess first
No terminal operation. 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.Stream;
public class Main {
public static void main(String[] args) {
List<Integer> scores = List.of(4, 9, 7);
Stream<Integer> doubled = scores.stream().map(score -> {
System.out.println("doubling " + score);
return score * 2;
});
System.out.println("done");
}
}
your turn
Your turn. Find the warm days.
On line 7, keep temperatures of 20 or more. On line 8, turn each one into text like 22C.
output
press run to see what happens
fix it
The name badges will not compile. Can you fix it?
output
press run to see what happens
- Java says a
Streamcannot become aList. What is missing from the end of the pipeline? maphands on another stream. A terminal operation has to gather the items into a list.- Remove the semicolon on line 8 and add
.collect(Collectors.toList());on a new line, then run.
nailed it
your data flows through pipelines now. :D
filterkeeps items,mapchanges them,collectgathers them.- Nothing runs until a terminal operation asks for results.
- A pipeline never changes its source list.
new words in your collection
- stream
- pipeline
- intermediate operation
- terminal operation
This lesson isn’t saved. A free account remembers every lesson you finish.