如何计算Java8流中按属性分组的对象分组中的多个和?

W Mii:

我正在使用一些数据进行一些计算。该对象具有几个数值属性。我已经实现了根据一个属性的类型来计算分组。但是需要对每个数值进行计算。那么,有什么方法可以解决这个问题?

Person p1 = new Person("p1","type1",18,3);
Person p2 = new Person("p2","type2",10,6);
Person p3 = new Person("p3","type1",5,8);

List<Person> personList = new ArrayList<>();
personList.add(p1);
personList.add(p2);
personList.add(p3);

Map<String, Integer> collect = 
        personList.stream().collect(
            Collectors.groupingBy(
                Person::getType,Collectors.summingInt(Person::getAge)
            )
        );

我希望每个属性和一个结果图的总和。映射的值是一个映射/数组/列表。例如:

type1 [23,11]
type2 [10,6]
名称:

正如评论中所指出的,在这里定义输出的类型很重要。要添加如何计划的要点,可以将Collectors.toMapcustom与配合使用mergeFunction

List<Person> personList = new ArrayList<>();
Map<String, Person> collect = personList.stream()
        .collect(Collectors.toMap(Person::getType, a -> a, (p1, p2) ->
                new Person(p1.getX(), p1.getType(),
                        p1.getAge() + p2.getAge(),
                        p1.getCode() + p2.getCode()))); // named the other attribute 'code'

现在,对于每个对象,type您都有一个求和Person整数值对象

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章