java 使用stream对list进行分组
使用Stream的collect方法可以对List进行分组。可以使用Collectors.groupingBy方法来进行分组。
假设有一个List
List<Person> persons = Arrays.asList(
new Person("Alice", 20),
new Person("Bob", 25),
new Person("Charlie", 30),
new Person("David", 20)
);
Map<Integer, List<Person>> groupedByAge = persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(groupedByAge);
运行这段代码会输出以下结果:
{20=[Person{name='Alice', age=20}, Person{name='David', age=20}], 25=[Person{name='Bob', age=25}], 30=[Person{name='Charlie', age=30}]}
可以看到,按照年龄进行分组后,每个年龄对应一个Person对象的列表
原文地址: http://www.cveoy.top/t/topic/iJZz 著作权归作者所有。请勿转载和采集!