我已创建HashMap<String,List<Integer>>
。现在我想通过替换第一张地图上的键和值来创建反向HashMap<Integer,List<String>>
。如何反转HashMap的键和值?
例如
原始HashMap中:{ A=[2,1], B=[1,3,4], C=[5], D=[3], E=[2,4] }
反转HashMap中:{ 1=[A,B], 2=[A,E], 3=[B,D], 4=[B,E], 5=[C] }
我已创建HashMap<String,List<Integer>>
。现在我想通过替换第一张地图上的键和值来创建反向HashMap<Integer,List<String>>
。如何反转HashMap的键和值?
例如
原始HashMap中:{ A=[2,1], B=[1,3,4], C=[5], D=[3], E=[2,4] }
反转HashMap中:{ 1=[A,B], 2=[A,E], 3=[B,D], 4=[B,E], 5=[C] }
实现以下伪代码:
Parameter: original map OM
Let RM be an empty map.
For all String S in OM:
For all integer I in the OM[S]:
If RM do not contains I:
Let RM[I] be an empty list.
Add S to RM[I].
Return RM.
尝试此。
HashMap<Integer,List<String>> reverse = new HashMap<>(original.size());
for(HashMap.Entry<String,List<Integer>> entry : original) {
for(Integer n : entry.getValue()) {
if(!reverse.containsKey(n)) { //Reverse doesn't have this number yet, create a new list at that key.
reverse.add(n,new ArrayList<>());
}
reverse.get(n).add(entry.getKey());
}
}
让我知道是否有一些错误,但先修补它!
HashMap<String, List<Integer>> hMap=new HashMap<String, List<Integer>>();
hMap.put("A",new ArrayList<Integer>(Arrays.asList(2,1)));
hMap.put("B",new ArrayList<Integer>(Arrays.asList(1,3,4)));
hMap.put("C",new ArrayList<Integer>(Arrays.asList(5)));
hMap.put("D",new ArrayList<Integer>(Arrays.asList(3)));
hMap.put("E",new ArrayList<Integer>(Arrays.asList(2,4)));
//Original HashMap: { A=[2,1], B=[1,3,4], C=[5], D=[3], E=[2,4] }
//Reversed HashMap: { 1=[A,B], 2=[A,E], 3=[B,D], 4=[B,E], 5=[C] }
HashMap<Integer,List<String>> result = new HashMap<>(hMap.size());
for(Map.Entry<String,List<Integer>> entry : hMap.entrySet()) {
for(Integer n : entry.getValue()) {
if(!result.containsKey(n)) {
result.put(n,new ArrayList<String>());
}
result.get(n).add(entry.getKey());
}
}
System.out.println(hMap);
System.out.println(result);
输出
{d = [3],E = [2,4],A = [2,1],B = [1,3,4],C = [ 5]}
{1 = [A,B],2 = [E,A],3 = [d,B],4 = [E,B],5 = [C]}
什么你的代码有问题吗?你不要求我们为你写,对吧:) – Pshemo
我相信你的意思是反转,回复意味着“回到以前的状态” –
创建一个新的'Map>'和循环。两次。完成。 –