sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

合并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(1, 1);
  12. list.add(map0);
  13. Map map1 = new HashMap();
  14. map1.put(3, 4);
  15. list.add(map1);
  16. Map map2 = new HashMap();
  17. map2.put(1, 2);
  18. list.add(map2);
  19. Map map3 = new HashMap();
  20. map3.put(1, 3);
  21. list.add(map3);
  22. Map map4 = new HashMap();
  23. map4.put(2, 2);
  24. list.add(map4);
  25. Map map5 = new HashMap();
  26. map5.put(2, 1);
  27. list.add(map5);
  28. Map map6 = new HashMap();
  29. map6.put(3, 1);
  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]}

https://blog.csdn.net/qq_24877569/article/details/52187388
posted on 2022-03-24 22:05  sunny123456  阅读(628)  评论(0编辑  收藏  举报