Java Stream 分组:使用 Collectors.groupingBy 对 List 进行分组
使用 Stream 的 collect 方法可以对 List 进行分组。可以使用 Collectors.groupingBy 方法来进行分组。
假设有一个 List<Person> 的列表,每个 Person 对象有一个属性 age,我们要按照年龄进行分组,可以使用下面的代码:
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 对象的列表。
原文地址: https://www.cveoy.top/t/topic/qqf3 著作权归作者所有。请勿转载和采集!