What can Collectors.groupingBy do in Java, and what are the common variations?
The method groupingBy builds a map out of a stream, and the keys of that map are worked out by a function that you give it.
The simplest form takes one function, and it groups the items by whatever that function returns.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan", "Katherine");
// Group the names by their first letter.
Map<Character, List<String>> byFirstLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println("grouped : " + byFirstLetter);
System.out.println("the A group : " + byFirstLetter.get('A'));
}
}
There are several variations of it, and they all take the same idea further.
The first variation adds a second function that says what to do with the items in each group. That is the version you want when you do not want a list of the items but a count of them, or a set, or a sum.
The second variation lets you say what kind of map to build, so that you get a map that keeps its keys in order instead of one that does not promise any order.
The third variation combines the two, so that you can have an ordered map whose values are also computed by a second function.
There is also a short form that does the most common of these, which is grouping the items and counting them all at once.
The next question in this topic shows how to use those variations.