温馨提示×

java中list groupby的用法是什么

小亿
363
2024-03-01 12:29:18
栏目: 编程语言

在Java中,可以使用Stream API中的Collectors.groupingBy()方法来对List进行分组操作。这个方法接受一个Function作为参数,该Function用于定义分组的依据,然后返回一个Map对象,其中key是分组的依据,value是属于该分组的元素列表。

以下是一个简单的示例,展示如何使用Collectors.groupingBy()方法对一个List进行分组操作:

假设有一个Student类:

public class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } 

然后我们有一个List

List<Student> students = new ArrayList<>(); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22)); students.add(new Student("Alice", 21)); students.add(new Student("Charlie", 20)); 

现在我们想要按照Student的name属性进行分组:

Map<String, List<Student>> groupedStudents = students.stream() .collect(Collectors.groupingBy(Student::getName)); 

这样就可以得到一个Map对象,其中key是Student的name属性值,value是属于该分组的Student对象列表。

在上面的示例中,groupedStudents的结果可能是这样的:

{ "Alice": [Student{name='Alice', age=20}, Student{name='Alice', age=21}], "Bob": [Student{name='Bob', age=22}], "Charlie": [Student{name='Charlie', age=20}] } 

0