List分组求和

来源:互联网 发布:郁乎苍苍的苍苍 编辑:程序博客网 时间:2024/04/27 19:37

一个list数据中,如何做到像mysql那样分组求和?

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by csucoderlee on 2017 04 13 上午11:14. * <p> * list中对相同name的内容,对count值加和,最终相同name合并成一条数据 */public class ListGroupSumList {    public static void main(String[] args) {        List<A> inList = new ArrayList<A>();        A a1 = new A().setId(1).setName("aaaa").setCount(1);        A a2 = new A().setId(2).setName("bbbb").setCount(4);        A a3 = new A().setId(3).setName("cccc").setCount(3);        A a4 = new A().setId(4).setName("aaaa").setCount(3);        inList.add(a1);        inList.add(a2);        inList.add(a3);        inList.add(a4);        Map<String, A> map = new HashMap<String, A>();        A tmpUser;        for(A oUser : inList) {            tmpUser = map.get(oUser.getName());            if (tmpUser != null) {                tmpUser.setCount(tmpUser.getCount() + oUser.getCount());            } else {                map.put(oUser.getName(), oUser);            }        }        List<A> returnList = new ArrayList<>();        for (A a : map.values()){            returnList.add(a);        }        System.out.print(returnList);    }    static class A {        private Integer id;        private String name;        private Integer count;        public Integer getId() {            return id;        }        public A setId(Integer id) {            this.id = id;            return this;        }        public String getName() {            return name;        }        public A setName(String name) {            this.name = name;            return this;        }        public Integer getCount() {            return count;        }        public A setCount(Integer count) {            this.count = count;            return this;        }    }}


0 0