How to swap keys and values in a Map elegantly

前端 未结 8 1873
滥情空心
滥情空心 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条回答
  •  萌比男神i
    2020-12-25 15:04

    As a hint to answer https://stackoverflow.com/a/42091477/8594421

    This only works, if the map is not a HashMap and does not contain duplicate values.

    Map newMap = oldMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    

    throws an exception

    java.lang.IllegalStateException: Duplicate key

    if there are values more than once.

    The solution:

    HashMap newMap = new HashMap<>();
    
    for(Map.Entry entry : oldMap.entrySet())
            newMap.put(entry.getValue(), entry.getKey());
    
    // Add inverse to old one
    oldMap.putAll(newMap);
    

提交回复
热议问题