Collectors

Collectors perform structured stream reductions into lists, maps, summaries, and grouped results.

Downstream collectors refine a group. groupingBy chooses each word's length as the key, while counting records how many words have that length.

Build grouped results

import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of(
                "sun", "map", "river", "cloud");
        var counts = words.stream().collect(
                Collectors.groupingBy(
                    String::length,
                    TreeMap::new,
                    Collectors.counting()));
        System.out.println(counts);

        var upper = words.stream().collect(
                Collectors.groupingBy(
                    String::length,
                    TreeMap::new,
                    Collectors.mapping(
                        String::toUpperCase,
                        Collectors.toList())));
        System.out.println(upper);
    }
}

Output:

{3=2, 5=2}
{3=[SUN, MAP], 5=[RIVER, CLOUD]}

TreeMap sorts the length keys. counting tallies each group. mapping(transform, downstream) first applies the transform to every element, then lets the downstream collector gather the results; here each group becomes a list of uppercased words via Collectors.toList().

A collector with unordered map output should not be used when exact presentation order is part of the requirement. Choose the map supplier deliberately.

Group song titles by artist with groupingBy and mapping.