You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java列表各实体属性求和并封装为对象的实现方法咨询

Java 列表属性求和实现方案

1. 先定义对应实体类

首先需要一个和数据结构匹配的实体类,用来封装每条数据的属性。如果是Java 16及以上版本,推荐用record(简洁且自动生成属性访问方法):

public record InputD3(int cashvalue, int cashInput, int profit) {}

如果是低版本Java,用普通类并补充构造方法、getter/setter:

public class InputD3 {
    private int cashvalue;
    private int cashInput;
    private int profit;

    public InputD3(int cashvalue, int cashInput, int profit) {
        this.cashvalue = cashvalue;
        this.cashInput = cashInput;
        this.profit = profit;
    }

    // 生成getter和setter方法
    public int getCashvalue() { return cashvalue; }
    public void setCashvalue(int cashvalue) { this.cashvalue = cashvalue; }
    public int getCashInput() { return cashInput; }
    public void setCashInput(int cashInput) { this.cashInput = cashInput; }
    public int getProfit() { return profit; }
    public void setProfit(int profit) { this.profit = profit; }
}

2. 实现属性求和的两种方式

方式一:传统遍历累加

适合所有Java版本,逻辑直观易懂:

// 假设inputList是你的原始数据列表
List<InputD3> inputList = Arrays.asList(
    new InputD3(100, 500, 400),
    new InputD3(100, 500, 400),
    new InputD3(100, 500, 400)
);

// 初始化求和对象,初始值为0
InputD3 sumObj = new InputD3(0, 0, 0);

// 遍历列表累加每个属性
for (InputD3 item : inputList) {
    sumObj.setCashvalue(sumObj.getCashvalue() + item.getCashvalue());
    sumObj.setCashInput(sumObj.getCashInput() + item.getCashInput());
    sumObj.setProfit(sumObj.getProfit() + item.getProfit());
}

// 将结果封装成单元素列表
List<InputD3> resultList = Collections.singletonList(sumObj);

方式二:Stream流Reduce操作

Java 8及以上版本可用,代码更简洁:

List<InputD3> inputList = Arrays.asList(
    new InputD3(100, 500, 400),
    new InputD3(100, 500, 400),
    new InputD3(100, 500, 400)
);

// 使用reduce合并所有元素的属性
Optional<InputD3> sumOptional = inputList.stream()
    .reduce((prev, curr) -> new InputD3(
        prev.getCashvalue() + curr.getCashvalue(),
        prev.getCashInput() + curr.getCashInput(),
        prev.getProfit() + curr.getProfit()
    ));

// 处理空列表情况,避免空指针
List<InputD3> resultList = sumOptional.map(Collections::singletonList)
    .orElse(Collections.emptyList());

如果用的是record,reduce里可以直接调用属性名(无需getter):

Optional<InputD3> sumOptional = inputList.stream()
    .reduce((prev, curr) -> new InputD3(
        prev.cashvalue() + curr.cashvalue(),
        prev.cashInput() + curr.cashInput(),
        prev.profit() + curr.profit()
    ));

注意事项

  • 如果列表可能为空,一定要处理Optional的空情况,避免抛出NullPointerException
  • 如果属性类型是Integer(非基本类型),累加时要先判断是否为null,比如:prev.getCashvalue() != null ? prev.getCashvalue() : 0

内容的提问来源于stack exchange,提问作者nightfury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:17:38