在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}]
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/904396.html