繁体   English   中英

如何总结对象数组列表的记录

[英]How to Summarize record of Array-list of Object

请看下面的问题。

    //Bean Class
public class Test {

    private int value;
    private int com_id;

    /**
     * @return the value
     */
    public int getValue() {
        return value;
    }

    /**
     * @param value the value to set
     */
    public void setValue(int value) {
        this.value = value;
    }

    /**
     * @return the com_id
     */
    public int getCom_id() {
        return com_id;
    }

    /**
     * @param com_id the com_id to set
     */
    public void setCom_id(int com_id) {
        this.com_id = com_id;
    }

}

主类

public class Test2 {

    public static void main(String[] args) {
        Test bean1 = new Test();
        Test bean2 = new Test();
        Test bean3 = new Test();
        Test bean4 = new Test();
        Test bean5 = new Test();

        //bean1
        bean1.setCom_id(1);
        bean1.setValue(10);
        //bean2 
        bean2.setCom_id(2);
        bean2.setValue(50);
        //bean3
        bean3.setCom_id(1);
        bean3.setValue(30);
        //bean4 
        bean4.setCom_id(1);
        bean4.setValue(20);
        //bean5
        bean5.setCom_id(2);
        bean5.setValue(20);

        //Arraylist of Test object
        ArrayList<Test> alltest = new ArrayList<Test>();
        alltest.add(bean1);
        alltest.add(bean2);
        alltest.add(bean3);
        alltest.add(bean4);
        alltest.add(bean5);

    }

}

现在我想要 ArrayList 的所有值的总和,其 com_id 与以下 answer_list com_id = 1 相同; val = 60 (10+30+20) com_id = 2; 价值 = 70 (50+20)

您可以使用 for 循环以旧方式执行此操作,也可以使用 Java 8 Streams 在一行(很长)中执行此操作:

List<Test> aggregated = 
    alltest.stream()
           .collect(Collectors.groupingBy(Test::getCom_id,
                                          Collectors.summingInt(Test::getValue)))
           .entrySet()
           .stream()
           .map(e-> new Test(e->getKey(),e->getValue())
           .collect(Collectors.toList());

解释 :

第一部分(直到第一个collect结束)应该创建一个Map<Integer,Integer> ,其中键是 Test 标识符,值是具有相同 ID 的所有 Test 实例的值的总和。

第二部分迭代该 Map 的条目,然后转换为测试实例列表。

请注意,这需要向带有两个参数的 Test 类添加一个构造函数。

public Test (int com_id, int value) {
    this.com_id = com_id;
    this.value = value;
}

这未经测试,因此可能包含拼写错误。

我完全同意,Ankur ......但这里至少有一些提示:

你想要一些逻辑,比如:

tempVar = 0
for all elements in my List:
    if the id of current element is what i need:
        add value of current element to tmpVar

暂无
暂无

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

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