java 分组后使用Collectorsreducing 对象属性进行累加 返回对象
假设我们有一个Person类,其中包含name和age属性。我们想要按照年龄分组,并将每个分组中的所有人的年龄进行累加,并返回一个Map,其中键是年龄,值是该年龄组中所有人的年龄之和。
我们可以使用Collectors.groupingBy对年龄进行分组,然后使用Collectors.reducing对分组中的每个人的年龄进行累加。
下面是一个示例代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("John", 25));
persons.add(new Person("Jane", 30));
persons.add(new Person("Tom", 25));
persons.add(new Person("Alice", 30));
Map<Integer, Integer> ageSumMap = persons.stream()
.collect(Collectors.groupingBy(Person::getAge,
Collectors.reducing(0, Person::getAge, Integer::sum)));
System.out.println(ageSumMap);
}
}
输出结果为:
{25=50, 30=60}
其中,{25=50, 30=60}表示年龄为25的组中所有人的年龄之和为50,年龄为30的组中所有人的年龄之和为60
原文地址: https://www.cveoy.top/t/topic/iZfI 著作权归作者所有。请勿转载和采集!