jdk 的Conllectors.groupingBy方法的两种方法用法
时间: 2024-10-24 08:05:57 浏览: 25
JDK的`Collectors.groupingBy()`方法是一个收集流元素的工具方法,用于将数据按照指定键进行分组。它有两种常见的用法:
1. **无泛型版本**:
```java
Map<KeyType, List<ValueType>> result = stream.collect(Collectors.groupingBy(Function.identity()));
```
这里,`Function.identity()`通常用作键生成器,表示每个元素本身作为键,值列表则包含该元素的所有实例。
2. **带泛型版本**:
```java
Map<KeyType, List<ValueType>> result = stream.collect(Collectors.groupingBy(element -> getKeyFromElement(element)));
```
这个版本更通用,通过传入一个函数`getKeyFromElement(element)`,你可以自定义如何从元素中提取键。这个函数应该返回一个`KeyType`类型的值。
举个例子,如果你有一个学生列表,你想按成绩分组,可以这样操作:
```java
List<Student> students = ...;
Map<Integer, List<Student>> groupedByScore = students.stream()
.collect(Collectors.groupingBy(Student::getScore));
```
在这里,`getScore`方法负责获取学生的分数,作为键。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)