使用Stream的collect方法可以对List进行分组。可以使用Collectors.groupingBy方法来进行分组。

假设有一个List的列表,每个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对象的列表

java 使用stream对list进行分组

原文地址: http://www.cveoy.top/t/topic/iJZz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录