How to swap keys and values in a Map elegantly

前端 未结 8 1866
滥情空心
滥情空心 2020-12-25 14:49

I already know how to do it the hard way and got it working - iterating over entries and swapping \"manually\". But i wonder if, like so many tasks, this one can be solved

8条回答
  •  天涯浪人
    2020-12-25 15:00

    If you don't have a choice to use a third party library, I don't consider the following code so ugly (though some scripting languages do have elegant ways of doing it):

    //map must be a bijection in order for this to work properly
    public static  HashMap reverse(Map map) {
        HashMap rev = new HashMap();
        for(Map.Entry entry : map.entrySet())
            rev.put(entry.getValue(), entry.getKey());
        return rev;
    }
    

提交回复
热议问题