之前遇到一個問題,一直困擾着。我的業務是:
map1 ->(100003,1),(100004,2),(100006,2)
map2 ->(100003,3),(100006,5)
map3 ->(100004,1),(100005,1)
根據相同的鍵合併爲表格:
100003 | 1 | 3 | 0 |
100004 | 2 | 0 | 1 |
100005 | 0 | 0 | 1 |
100006 | 2 | 0 | 0 |
當時一直很糾結,雖然最後處理出來,但是中間過程很繞,如果有更簡單的方法,請提供,謝謝!
思路(根據上面的map1,map2,map3來舉例):
1.map中數據可能會有重複,分別遍歷map,相同鍵相加值,放入一個List<Map>中。
2.循環list,map1,map2,map3分別對比,如果有相同的key -> continue;若不相同,則put(key,0)
3.去除list中相同的數據,通過set,新的List<Map>接收
4.整理新的List<Map>,用Map<Integer,List>來接收最後的數據,Integer爲我所需要的key,list則是後面所對應的值
可能我寫的思路不是特別清晰,所以下面貼各個思路的代碼:
第一步:
List<Map<Integer ,Integer>> listMap = new ArrayList<Map<Integer,Integer>>();//接收相同鍵值相加的map
Map<Integer, Integer> resultPhonesMap = new HashMap<Integer,Integer>();//中間map,處理相同鍵值相加
Iterator<Map.Entry<Integer,Integer>> it = phonesMap.entrySet().iterator();//相當於上面內容中的map1
while(it.hasNext()){//遍歷map1
Map.Entry<Integer, Integer> entry = it.next();
int key = entry.getKey();
int value = entry.getValue();
if(resultPhonesMap.containsKey(key)){//如果map包含相同的key
int phonesTimes = resultPhonesMap.get(key);//得到key所對應的值
phonesTimes += value;//進行相加
resultPhonesMap.replace(key, phonesTimes);//替換map中之前的值
}else{//如果不包含
resultPhonesMap.put(key, value);//則放入之前的key和之前的值
}
}
listMap.add(resultPhonesMap);//中間處理map放入List<Map>中
for(int i = 0;i< listMap.size();i++){//循環List<Map>
Map<Integer, Integer> map2 = listMap.get(i);//獲取list中每一個map
Iterator<Integer> result = map2.keySet().iterator();
while (result.hasNext()) {//進行遍歷
Integer key = result.next();
if(!resultPhonesMap.containsKey(key)){//map1不包含當前key,則put(key,0)
resultPhonesMap.put(key, 0);
listMap.add(resultPhonesMap);
}else if(!resultOpenAccountMoreMap.containsKey(key)){//map2
resultOpenAccountMoreMap.put(key, 0);
listMap.add(resultOpenAccountMoreMap);
}else if(!resultRemoteMap.containsKey(key)){//map3
resultRemoteMap.put(key, 0); listMap.add(resultRemoteMap); } } }第三步:
Set set = new HashSet(); //set:去除list中重複數據
List<Map> newList = new ArrayList<Map>(); //接收無重複數據的map
for (Map map:listMap) {
if(set.add(map)){
newList.add(map);
}
}
第四步:
Map<Integer, List> map = new HashMap<>(); //返回最後結果
for (Map m : newList) {//循環上面新的List<Map>
Iterator<Integer> result = m.keySet().iterator();
while (result.hasNext()) {//遍歷數據
Integer key = result.next();
if (!map.containsKey(key)) {//如果不包含key
List newList1 = new ArrayList<>();
newList1.add(m.get(key)); //list中添加數據
map.put(key, newList1); //key,list
} else {//包含key,則添加key對應的值
map.get(key).add(m.get(key));
}
}
}