agent_bean
agent_bean

Reputation: 1575

How to add properties of an object using Streams in Java?

I'm trying to learn more about stream Collectors. I have a list of person called people. I am grouping by name. I would like to sum up all the properties of that particular person, that is of interest to me, and return a new object with all the properties summed.

For example Tom would have a salary of 36000, and age of 36.

I am able to sum up the items individually by iterating over each property.

How can I sum up the individual properties in a single pass?

public class Hello {
    
    private static Integer collect2;

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();
        
        // Person class with Name, salary, age.
        Person person = new Person("Tom",12000,12);

        people.add(person);
        people.add(person);
        people.add(person);

        Map<String, List<Person>> collect = people.stream().collect(
            Collectors.groupingBy(Person::getName));    

        Integer age = collect.get("Tom").stream()
        .map(Person::getAge).collect(Collectors.summingInt(Integer::intValue));
        
        Integer salary = collect.get("Tom").stream()
        .map(Person::getSalary).collect(Collectors.summingInt(Integer::intValue));

        System.out.println(age + "\n" + salary);
    }
}

Upvotes: 0

Views: 548

Answers (1)

Ihar Hulevich
Ihar Hulevich

Reputation: 181

Please try the following code:

people.stream().collect(
    groupingBy(
    p -> p.name, 
    collectingAndThen(reducing((a, b) -> new Person(a.name, a.salary + b.salary, a.age + b.age)), Optional::get)
    )
).forEach((id, p) -> System.out.println(p));

or

people.stream().collect(
    Collectors.toMap(p -> p.name, Function.identity(),
        (a, b) -> new Person(a.name, a.salary + b.salary, a.age + b.age))
).forEach((id, p) -> System.out.println(p));

Upvotes: 3

Related Questions