使用Collectors.reducing方法对对象属性进行累加,可以通过以下步骤实现:

  1. 定义一个BinaryOperator,用于将两个对象属性相加。
  2. 使用Collectors.reducing方法,传入上述BinaryOperator以及初始值。
  3. 将Collectors.reducing方法作为参数传递给Collectors.collectingAndThen方法,将结果转换为期望的对象。

以下是一个示例代码:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 20));
        personList.add(new Person("Bob", 30));
        personList.add(new Person("Charlie", 40));

        Person result = personList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.reducing((p1, p2) -> new Person(p1.getName(), p1.getAge() + p2.getAge())),
                        Optional::get
                ));

        System.out.println(result.getName()); // 输出 "AliceBobCharlie"
        System.out.println(result.getAge()); // 输出 90
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

在上述示例中,使用Collectors.reducing方法对Person对象的age属性进行累加。最终通过Collectors.collectingAndThen方法将结果转换为Person对象

java Collectorsreducing 对象属性进行累加 返回对象

原文地址: https://www.cveoy.top/t/topic/iZfH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录