How to swap keys and values in a Map elegantly

前端 未结 8 1831
滥情空心
滥情空心 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<String, Integer> map = new HashMap<>();
    Map<Integer, String> swapped = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    
    0 讨论(0)
  • 2020-12-25 15:23

    If you had access to apache commons-collections, you could have used MapUtils.invertMap.

    Note: The behaviour in case of duplicated values is undefined.

    (Replying to this as this is the first google result for "java invert map").

    0 讨论(0)
提交回复
热议问题