假如一个map数据:
key:value
0: [1,5,10]
1: [1,2,15]
2: [2,3]
将map的key和value反向存储得到:
key:value
1: [0,1]
5: [0]
10: [0]
2: [1,2]
15: [1]
3: [2]
@Test
public void testConvertMap(){
Map<Integer,List<Integer>> map=new HashMap<>();
map.put(0,Arrays.asList(1,5,10));
map.put(1,Arrays.asList(1,2,15));
map.put(2,Arrays.asList(2,3));
System.out.println("map:"+map.toString());
//将map的key和value进行反转存储
Map<Integer,List<Integer>> result=new HashMap<>();
for(Map.Entry<Integer, List<Integer>> values:map.entrySet()){
Integer mapKey=values.getKey();
List<Integer> mapValues=values.getValue();
for(Integer value:mapValues){
if(result.containsKey(value)){
List<Integer> list=result.get(value);
list.add(mapKey);
result.put(value,list);
}else{
List<Integer> list=new ArrayList<>();
list.add(mapKey);
result.put(value,list);
}
}
}
System.out.println("convert map:"+result.toString());
//map:{0=[1, 5, 10], 1=[1, 2, 15], 2=[2, 3]}
//convert map:{1=[0, 1], 2=[1, 2], 3=[2], 5=[0], 10=[0], 15=[1]}
}