首页 > 解决方案 > 如何使用 Java 中的 Streams 添加对象的属性?

问题描述

我正在尝试了解有关流收集器的更多信息。我有一个名为 people 的人的列表。我按名称分组。我想总结我感兴趣的那个特定人的所有属性,并返回一个包含所有属性总和的新对象。

例如,汤姆的薪水为 36000,年龄为 36 岁。

我可以通过迭代每个属性来单独总结这些项目。

如何在一次通过中总结各个属性?

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

标签: java

解决方案


请尝试以下代码:

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

或者

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

推荐阅读