collectors.groupingby()
时间: 2024-01-25 10:03:12 浏览: 67
java8 集合 多字段 分组 统计个数代码
5星 · 资源好评率100%
The `collectors.groupingBy()` method is a method available in the Java Stream API that allows you to group the elements of a stream into a map, where the keys of the map are determined by a specified grouping function.
The method takes as input a grouping function that determines how the elements of the stream should be grouped, and returns a `Collector` object that can be used to accumulate the elements of the stream into a map.
Here is an example usage of the `collectors.groupingBy()` method:
```
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
Map<Integer, List<String>> wordGroups = words.stream().collect(Collectors.groupingBy(String::length));
```
In this example, the `groupingBy()` method is used to group the words in the `words` list by their length. The resulting `wordGroups` map will have keys representing the lengths of the words, and values that are lists of words with that length. The output of this code will be:
```
{5=[apple, cherry], 6=[banana], 4=[date], 10=[elderberry]}
```
阅读全文