首页 > 编程技术 > java

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

发布时间:2021-6-10 15:00 点击:1430

这篇文章主要介绍了java8 Stream list to Map key 重复 value合并到Collectio的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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

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

List<String> list = Lists.newArrayList("1", "2", "3", "1");
        Map<String, List<String>> map = list.stream().collect(Collectors.toMap(key -> key,
                value -> Lists.newArrayList(value),
                (List<String> newValueList, List<String> 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<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("id", 1);
		map1.put("value", 2);
		list.add(map1);
		
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("id", 1);
		map2.put("value", 5);
		list.add(map2);
		
		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("id", 2);
		map3.put("value", 5);
		list.add(map3);
		
		Map<String, Object> map4 = new HashMap<String, Object>();
		map4.put("id", 2);
		map4.put("value", 4);
		list.add(map4);
		
		Map<String, Object> map5 = new HashMap<String, Object>();
		map5.put("id", 1);
		map5.put("value", 4);
		list.add(map5);
		
		//id相等value相加(合并id相同数据)
		System.out.println("原始数据:"+list);
		
		//方法一
		Map<String, Object> result1 = new HashMap<String, Object>();
		for(Map<String, Object> 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<String, Map<String, Object>> result2 = new HashMap<String, Map<String,Object>>();
		for(Map<String, Object> 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);
 
	}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

您可能感兴趣的文章:

相关文章