合并List<Map<String,String>>中的重复数据并对某个字段做累加

package demo1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class mergeData {
	public static void main(String[] args) {
		List<Map<String, String>> l = new ArrayList<Map<String, String>>();
		Map<String, String> oneMap = new HashMap<String, String>();
		oneMap.put("gsId", "8000");
		oneMap.put("gsName", "总部集中处理中心");
		oneMap.put("type", "D");
		oneMap.put("yybcount", "3");
		l.add(oneMap);
		Map<String, String> twoMap = new HashMap<String, String>();
		twoMap.put("gsId", "8008");
		twoMap.put("gsName", "南京长江路证券营业部");
		twoMap.put("type", "H");
		twoMap.put("yybcount", "14");
		l.add(twoMap);

		List<Map<String, String>> twoList = new ArrayList<Map<String, String>>();
		Map<String, String> oneMap1 = new HashMap<String, String>();
		oneMap1.put("gsId", "8008");
		oneMap1.put("gsName", "南京长江路证券营业部");
		oneMap1.put("type", "H");
		oneMap1.put("yybcount", "5");
		twoList.add(oneMap1);
		Map<String, String> twoMap2 = new HashMap<String, String>();
		twoMap2.put("gsId", "8008");
		twoMap2.put("gsName", "南京止马营证券营业部");
		twoMap2.put("type", "F");
		twoMap2.put("yybcount", "9");
		twoList.add(twoMap2);

		l.addAll(twoList);

		List<Map<String, String>> countList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < l.size(); i++) {
			String gsId = l.get(i).get("gsId");
			String type = l.get(i).get("type");
			int flag = 0;// 0为新增数据,1为增加count
			for (int j = 0; j < countList.size(); j++) {
				String gsId_ = countList.get(j).get("gsId");
				String type_ = countList.get(j).get("type");

				if (gsId.equals(gsId_) && type.equals(type_)) {
					int sum = Integer.parseInt(l.get(i).get("yybcount"))
							+ Integer.parseInt(countList.get(j).get("yybcount"));
					countList.get(j).put("yybcount", sum + "");
					flag = 1;
					continue;
				}
			}
			if (flag == 0) {
				countList.add(l.get(i));
			}
		}
		for (Map<String, String> map : countList) {
			System.out.println(map);
		}
	}
}

返回结果:

{gsName=总部集中处理中心, yybcount=3, type=D, gsId=8000}
{gsName=南京长江路证券营业部, yybcount=19, type=H, gsId=8008}
{gsName=南京止马营证券营业部, yybcount=9, type=F, gsId=8008}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nizhengjia888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值