简体   繁体   中英

How to calculate multiple sum in an object grouping by a property in Java8 stream?

I'm doing some calculations with some data. The object has several numeric properties. I have achieved calculating grouping by the type on one property. But the need is to calculate on each numeric value. So, is there any method to solve this problem?

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)
            )
        );

I expect the sum of each property and a single result map. The value of the map is a map/array/list. For example:

type1 [23,11]
type2 [10,6]

As pointed out in comments as well, defining the type of your output matters here. To add a gist of how you can plan to do it, you can use Collectors.toMap with custom mergeFunction as :

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'

Now, against every type you have a Person object with integer values summed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM