天天看點

合并map中key相同的value

這幾天工作中遇到的問題,背景傳回的是一個List<Map<Object,Object>>數組,其中每個map中隻有一組值,但是這些map中有key相同的,需要将key相同的value合并成一個list

具體要求如下

List<Map> list = new ArrayList<>();

        Map map0 = new HashMap();

        map0.put(1, 1);

        list.add(map0);

        Map map1 = new HashMap();

        map1.put(3, 4);

        list.add(map1);

        Map map2 = new HashMap();

        map2.put(1, 2);

        list.add(map2);

        Map map3 = new HashMap();

        map3.put(1, 3);

        list.add(map3);

        Map map4 = new HashMap();

        map4.put(2, 2);

        list.add(map4);

        Map map5 = new HashMap();

        map5.put(2, 1);

        list.add(map5);

        Map map6 = new HashMap();

        map6.put(3, 1);

        list.add(map6);

        // 要求将上面的List<Map>中的map中key相同的value合并

        // 最終得到下面的結果Map<Object,List>,其中幾個map分别為

        // 1->[1,2,3]

        // 2->[2,1]

        // 3->[4,3]

  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import java.util.Map;
  6. public class CombineVale {
  7. public static void main(String[] args) {
  8. // TODO Auto-generated method stub
  9. List<Map> list = new ArrayList<>();
  10. Map map0 = new HashMap();
  11. map0.put( , );
  12. list.add(map0);
  13. Map map1 = new HashMap();
  14. map1.put( , );
  15. list.add(map1);
  16. Map map2 = new HashMap();
  17. map2.put( , );
  18. list.add(map2);
  19. Map map3 = new HashMap();
  20. map3.put( , );
  21. list.add(map3);
  22. Map map4 = new HashMap();
  23. map4.put( , );
  24. list.add(map4);
  25. Map map5 = new HashMap();
  26. map5.put( , );
  27. list.add(map5);
  28. Map map6 = new HashMap();
  29. map6.put( , );
  30. list.add(map6);
  31. // 要求将上面的List<Map>中的map中key相同的value合并
  32. // 最終得到下面的結果List<Map<Object,List>>,其中三個map分别為
  33. // 1->[1,2,3]
  34. // 2->[2,1]
  35. // 3->[4,3]
  36. Map m = mapCombine(list);
  37. System.out.println(m);
  38. }
  39. public static Map mapCombine(List<Map> list) {
  40. Map<Object, List> map = new HashMap<>();
  41. for (Map m : list) {
  42. Iterator<Object> it = m.keySet().iterator();
  43. while (it.hasNext()) {
  44. Object key = it.next();
  45. if (!map.containsKey(key)) {
  46. List newList = new ArrayList<>();
  47. newList.add(m.get(key));
  48. map.put(key, newList);
  49. } else {
  50. map.get(key).add(m.get(key));
  51. }
  52. }
  53. }
  54. return map;
  55. }
  56. }

輸出結果如下{1=[1, 2, 3], 2=[2, 1], 3=[4, 1]}