這幾天工作中遇到的問題,背景傳回的是一個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]
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- public class CombineVale {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- List<Map> list = new ArrayList<>();
- Map map0 = new HashMap();
- map0.put( , );
- list.add(map0);
- Map map1 = new HashMap();
- map1.put( , );
- list.add(map1);
- Map map2 = new HashMap();
- map2.put( , );
- list.add(map2);
- Map map3 = new HashMap();
- map3.put( , );
- list.add(map3);
- Map map4 = new HashMap();
- map4.put( , );
- list.add(map4);
- Map map5 = new HashMap();
- map5.put( , );
- list.add(map5);
- Map map6 = new HashMap();
- map6.put( , );
- list.add(map6);
- // 要求将上面的List<Map>中的map中key相同的value合并
- // 最終得到下面的結果List<Map<Object,List>>,其中三個map分别為
- // 1->[1,2,3]
- // 2->[2,1]
- // 3->[4,3]
- Map m = mapCombine(list);
- System.out.println(m);
- }
- public static Map mapCombine(List<Map> list) {
- Map<Object, List> map = new HashMap<>();
- for (Map m : list) {
- Iterator<Object> it = m.keySet().iterator();
- while (it.hasNext()) {
- Object key = it.next();
- if (!map.containsKey(key)) {
- List newList = new ArrayList<>();
- newList.add(m.get(key));
- map.put(key, newList);
- } else {
- map.get(key).add(m.get(key));
- }
- }
- }
- return map;
- }
- }
輸出結果如下{1=[1, 2, 3], 2=[2, 1], 3=[4, 1]}