Reversing a HashMap from Map to Map>

后端 未结 4 1113
遥遥无期
遥遥无期 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:29

    I'd do something similar (but if you must do this kind of thing frequently, consider Guava), only replacing the List with Set (seems a little more consistent) and prefilling the reversemap:

    private Map> reverseMap(Map permissions) {
        Map> returnvalue = new HashMap>();
        returnvalue.put(Boolean.TRUE, new HashSet());
        returnvalue.put(Boolean.FALSE, new HashSet());
        for (Entry entry : permissions.entrySet()) 
            returnvalue.get(entry.getValue()).add(entry.getKey());
        return returnvalue;
    }
    

提交回复
热议问题