collectors.groupingby()
时间: 2024-01-25 12:03:12 浏览: 21
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]}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)