List分组求和

一个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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值