collectors.groupingby() 分组封装一个对象
时间: 2024-01-25 22:03:39 浏览: 73
collectors.groupingby()方法是Java 8中的一个工具,用于将一个集合中的元素按照指定的规则进行分组,并将分组后的元素封装在一个对象中。
具体来说,该方法接受一个Function类型的参数,该函数用于指定分组的规则,然后返回一个Map类型的结果,其中键是分组的依据,值是一个列表,包含了所有符合该依据的元素。
例如,假设有一个Student类,其中包含了姓名、年龄、性别等属性:
```
class Student {
String name;
int age;
String gender;
// getters and setters
}
```
现在有一个Student列表,想要按照性别进行分组,可以使用如下代码:
```
List<Student> students = Arrays.asList(
new Student("Tom", 18, "Male"),
new Student("Alice", 20, "Female"),
new Student("John", 19, "Male"),
new Student("Mary", 21, "Female")
);
Map<String, List<Student>> groupedStudents = students.stream()
.collect(Collectors.groupingBy(Student::getGender));
```
上述代码中,使用了stream()方法将List转换为流,然后通过collect()方法进行分组操作,其中groupingBy()方法传入了一个lambda表达式(Student::getGender),用于指定按照性别进行分组。最后得到的结果是一个Map类型的对象,其中键是性别,值是一个列表,包含了所有符合该性别的Student对象。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)