java · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A decides what collect builds.
Collectors.toList() is one collector of many. glues strings into one sentence. splits items into a true pile and a false pile. Each is a recipe, and collect follows it.
is the power tool. groupingBy(word -> word.length()) builds a map from each length to the words that long. Add a second collector to gather each group differently: counting() turns a group into its size, as a Long, a whole number with more room than int.
Want the keys in order? Pass a map maker in the middle: groupingBy(key, TreeMap::new, counting()). A TreeMap keeps its keys sorted, so reports come out the same every time.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> votes = List.of("pizza", "curry", "pizza", "tacos", "curry", "pizza");
Map<String, Long> tally = votes.stream()
.collect(Collectors.groupingBy(vote -> vote, TreeMap::new, Collectors.counting()));
System.out.println(tally);
System.out.println(votes.stream().distinct().collect(Collectors.joining(" | ")));
System.out.println(List.of(3, 8, 12, 5).stream()
.collect(Collectors.partitioningBy(n -> n > 6)));
}
} vote -> vote uses each vote as its own key, which is how you count repeats.
guess first
Pets by first letter. 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.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> pets = List.of("cat", "cow", "dog", "duck", "cat");
Map<String, Long> byLetter = pets.stream()
.collect(Collectors.groupingBy(pet -> pet.substring(0, 1), TreeMap::new, Collectors.counting()));
System.out.println(byLetter);
}
}
your turn
Your turn. Read out the pizza order.
On line 8, use Collectors.joining to glue the toppings together with a separator of your choice, like ", ".
output
press run to see what happens
fix it
The towns come out jumbled. Can you fix it?
output
press run to see what happens
- The counts are right but the towns are jumbled. What kind of map does
groupingBybuild? - Without a map maker,
groupingByuses aHashMap, which keeps no order. ATreeMapsorts its keys. - Add
TreeMap::newas the middle argument on line 8 and importjava.util.TreeMap, then run.
nailed it
your streams build reports now. :D
- A collector tells
collectwhat to build. groupingBywithcounting()makes a table of counts.- Pass
TreeMap::newto keep the keys sorted.
new words in your collection
- collector
- groupingBy
- joining
- partitioningBy
This lesson isn’t saved. A free account remembers every lesson you finish.