在Java中,可以使用StreamAPI中的Collectors.groupingBy()方法来对List进行分组操作
在Java中,可以使用StreamAPI中的Collectors.groupingBy()
方法来对List进行分组操作。这个方法接受一个Function作为参数,该Function用于定义分组的依据,然后返回一个Map对象,其中key是分组的依据,value是属于该分组的元素列表。
以下是一个简单的示例,展示如何使用Collectors.groupingBy()
方法对一个List进行分组操作:
假设有一个Student类:
publicclassStudent{
privateStringname;
privateintage;
publicStudent(Stringname,intage){
this.name=name;
this.age=age;
}
publicStringgetName(){
returnname;
}
publicintgetAge(){
returnage;
}
}
然后我们有一个List:
List<Student>students=newArrayList<>();
students.add(newStudent("Alice",20));
students.add(newStudent("Bob",22));
students.add(newStudent("Alice",21));
students.add(newStudent("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}]
}
版权声明
本文仅代表作者观点,不代表博信信息网立场。