java8 Stream list to Map key 重复 value合并到Collectio的操作

java8 Stream list to Map key 重复 value合并到Collectio

关于把list转换成key value的map有很多博客上都有实现,这里是一个把value放入到集合中去

List list = Lists.newArrayList("1", "2", "3", "1");
        Map> map = list.stream().collect(Collectors.toMap(key -> key,
                value -> Lists.newArrayList(value),
                (List newValueList, List oldValueList) -> {
                    oldValueList.addAll(newValueList);
                    return oldValueList;
                }));
        System.out.println(JSON.toJSONString(map));

类似的,你的list泛型可以是一个bean,取bean的属性当key或者value,转换成一个集合

结果:

{"1":["1","1"],"2":["2"],"3":["3"]}

list中Map合并重复数据(map中key相等的value值相加)

public static void main(String[] args) {
		List> list = new ArrayList>();
		Map map1 = new HashMap();
		map1.put("id", 1);
		map1.put("value", 2);
		list.add(map1);
		
		Map map2 = new HashMap();
		map2.put("id", 1);
		map2.put("value", 5);
		list.add(map2);
		
		Map map3 = new HashMap();
		map3.put("id", 2);
		map3.put("value", 5);
		list.add(map3);
		
		Map map4 = new HashMap();
		map4.put("id", 2);
		map4.put("value", 4);
		list.add(map4);
		
		Map map5 = new HashMap();
		map5.put("id", 1);
		map5.put("value", 4);
		list.add(map5);
		
		//id相等value相加(合并id相同数据)
		System.out.println("原始数据:"+list);
		
		//方法一
		Map result1 = new HashMap();
		for(Map map : list){
			String id = map.get("id").toString();
			Long value = Long.parseLong(map.get("value").toString());
			if(result1.containsKey(id)){
				Long temp = Long.parseLong(result1.get(id).toString());
				value += temp;
			}
			result1.put(id, value);
		}
		System.out.println("合并后的数据:"+result1);
		
		//方法二
		Map> result2 = new HashMap>();
		for(Map map : list){
			String id = map.get("id").toString();
			Long value = Long.parseLong(map.get("value").toString());
			if(result2.containsKey(id)){
				Long temp = Long.parseLong(result2.get(id).get("value").toString());
				value += temp;
				result2.get(id).put("value", value);
				continue;
			}
			result2.put(id, map);
		}
		System.out.println("合并后的数据2:"+result2);
 
	}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(java8 Stream list to Map key 重复 value合并到Collectio的操作)