Java invert map

前端 未结 8 1367
南旧
南旧 2020-11-30 09:33

I need create inverse map - select unique values and for them find keys. Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not

8条回答
  •  难免孤独
    2020-11-30 10:09

    To get an inverted form of a given map in java 8:

    public static  Map inverseMap(Map sourceMap) {
        return sourceMap.entrySet().stream().collect(
            Collectors.toMap(Entry::getValue, Entry::getKey,
               (a, b) -> a) //if sourceMap has duplicate values, keep only first
            );
    }
    

    Example usage

    Map map = new HashMap();
    
    map.put(1, "one");
    map.put(2, "two");
    
    Map inverted = inverseMap(map);
    

提交回复
热议问题