Video in progress

Strong Junior 🌊 Streams and lambdas

How do you group elements with Collectors.groupingBy() and get the count in each group?

groupingBy(classifier) builds a Map<K, List<T>> by key. If you pass a downstream collector as the second argument, you get something other than a list: with counting() you get a count for each key.

📖 Answer

record Student(String name, String city, int score) {}

Map<String, List<Student>> byCity = students.stream()
        .collect(Collectors.groupingBy(Student::city));
// {Toshkent=[...], Samarqand=[...]}

Map<String, Long> countByCity = students.stream()
        .collect(Collectors.groupingBy(Student::city, Collectors.counting()));
// {Toshkent=12, Samarqand=5}

Note that counting() returns Long, not Integer. If you declare Map<String, Integer>, the compiler reports an error.

The result is a HashMap, so the key order isn't guaranteed. If you need order, pass a map factory:

Map<String, Long> sorted = students.stream()
        .collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));

If the classifier returns null, you get an NPE: "element cannot be mapped to a null key". If the city can be empty, handle it with something like s -> Objects.requireNonNullElse(s.city(), "noma'lum").

Simple grouping can be understood as Java's counterpart of SQL's GROUP BY. But for grouping data in a database, it's cheaper to do the GROUP BY in the query itself.