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); }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- Java提效神器Stream的一些冷門技巧匯總
- Java8 實現stream將對象集合list中抽取屬性集合轉化為map或list
- Java中List轉Map List實現的幾種姿勢
- 關於List、Map、Stream初始化方式
- Java之map的常見用法講解與五種循環遍歷實例代碼理解