如何反转HashMap的键和值?

时间:2013-08-31 15:24:48

标签: java dictionary hashmap iterator

我创建了一个HashMap<String,List<Integer>>。现在我想通过替换第一张地图中的键和值来创建反向HashMap<Integer,List<String>>

例如,

原始哈希地图:{ 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] }

3 个答案:

答案 0 :(得分:3)

实现以下伪代码:

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.

答案 1 :(得分:2)

    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]}

答案 2 :(得分:-1)

试试这个。

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());
    }
}

如果有错误,请告诉我,但先修补一下!