java - How to Summarize record of Array-list of Object -
please following problem.
//bean class public class test { private int value; private int com_id; /** * @return value */ public int getvalue() { return value; } /** * @param value value set */ public void setvalue(int value) { this.value = value; } /** * @return com_id */ public int getcom_id() { return com_id; } /** * @param com_id com_id set */ public void setcom_id(int com_id) { this.com_id = com_id; } }
main class
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); } }
now want arraylist sum of value com_id same follow answer_list com_id = 1; val = 60 (10+30+20) com_id = 2; val = 70 (50+20)
you can old way loops, or in 1 (very long) line using 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());
explanation :
the first part (until end of first collect
) should create map<integer,integer>
, key test identifier , value sum of values of test instances having same id.
the second part iterates on entries of map , tranforms list of test instances.
note requires adding constructor test class taking 2 parameters.
public test (int com_id, int value) { this.com_id = com_id; this.value = value; }
this not tested, may contain typos.
Comments
Post a Comment