繁体   English   中英

如何将相同 object 类型列表中相同字段的值汇总为一个 object

[英]How to sum up values of same field from the list of the same object type to just one object

假设有一个 class Obj

class Obj {
BigDecimal a;
BigDecimal b;
BigDecimal c;
BigDecimal d;
BigDecimal e;
BigDecimal f;
}

并且您有一个具有不同 'a',...,'f' 值的多个 Obj 实例的列表,即List<Obj> objList 例如,此 object 的 JSON 响应如下所示:

 {
    "a": 5,
    "b": 6,
    "c": 7,
    "d": 8,
    "e": 9,
    "f": 10,
},
{
    "a": 11,
    "b": 12,
    "c": 13,
    "d": 14,
    "e": 15,
    "f": 16,
},

And my question is how can I find in Java with streams how to sum the BigDecimal values from each object in list and return one object with total a, b, c, d, e, f? 根据示例,我想实现 JSON 响应如下所示:

{
    "a": 16,
    "b": 18,
    "c": 20,
    "d": 22,
    "e": 24,
    "f": 26,
}

我尝试使用这个Java8: sum values from specific field of the objects in a list solution 但它不适用于 BigDecimals 我不知道当 class 有很多字段时如何处理它

您可以尝试以下类似的方法,我使用相同的 class Obj 来保持字段的总和并仅在列表中循环一次

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class MyFirstJavProgram {
    public static void main(String[] args) {

        List<Obj> myList = new ArrayList<>();
        myList.add(new Obj(BigDecimal.ONE,BigDecimal.valueOf(2L),BigDecimal.valueOf(5L)));
        myList.add(new Obj(BigDecimal.ONE,BigDecimal.valueOf(5L),BigDecimal.valueOf(8L)));
        Obj sumOf = new Obj(BigDecimal.ZERO,BigDecimal.ZERO,BigDecimal.ZERO);
        myList.stream().forEach(o -> {
            sumOf.a = sumOf.a.add(o.a);
            sumOf.b = sumOf.b.add(o.b);
            sumOf.c = sumOf.c.add(o.c);
        });
        System.out.println(sumOf);


    }
}
class Obj {
    BigDecimal a;
    BigDecimal b;
    BigDecimal c;
    Obj(BigDecimal a, BigDecimal b,BigDecimal c){
        this.a=a;
        this.b=b;
        this.c=c;
    }

    @Override
    public String toString() {
        return "Obj{" +
                "a=" + a +
                ", b=" + b +
                ", c=" + c +
                '}';
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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