Reversing a HashMap from Map to Map>

后端 未结 4 1112
遥遥无期
遥遥无期 2021-01-19 04:11

Is there a more elegant/built-in way to reverse the keys and values of a Hashmap?

I currently have the following.

private Map

        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-19 04:24

    You might consider using one of Guava's Multimap implementations. For example:

    private Multimap reverseMap(Map permissions) {
       Multimap multimap = ArrayListMultimap.create();
       for (Map.Entry entry : permissions.entrySet()) {
          multimap.put(entry.getValue(), entry.getKey());
       }
       return multimap;
    }
    

    Or more generally:

    private static  Multimap reverseMap(Map source) {
       Multimap multimap = ArrayListMultimap.create();
       for (Map.Entry entry : source.entrySet()) {
          multimap.put(entry.getValue(), entry.getKey());
       }
       return multimap;
    }
    

提交回复
热议问题