Junior — Middle
What arguments and parameters does the groupingBy method from the Collectors class in Java expect?
sobes.tech AI
Answer from AI
The groupingBy method from the Collectors class in Java is used to group stream elements by a key, which is determined by a classification function.
Main argument options:
-
groupingBy(Function<? super T, ? extends K> classifier)- Takes a function that returns a grouping key for each element.
- Returns a
Collector<T, ?, Map<K, List<T>>>, where the values are lists of elements grouped by key.
-
groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)- Besides the classification function, it accepts another collector applied to each group.
- Allows, for example, counting the number of elements in each group, collecting them into a set, etc.
-
groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)- Allows specifying a specific map implementation (e.g.,
TreeMapinstead ofHashMap).
- Allows specifying a specific map implementation (e.g.,
Example usage:
List<String> names = Arrays.asList("Anna", "Bob", "Alice", "Brian", "Amanda");
Map<Character, List<String>> grouped = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
// grouped will contain keys 'A' and 'B' with corresponding lists of names
And an example with a downstream collector:
Map<Character, Long> countByFirstLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0), Collectors.counting()));
// counts the number of names for each letter