×

java · level 3 · unit 3 · lesson 4

  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

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.