How to swap keys and values in a Map elegantly

前端 未结 8 1894
滥情空心
滥情空心 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:10

    Map map = new HashMap<>();
    Map swapped = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    

提交回复
热议问题