Convert Set> to HashMap

后端 未结 6 1348
礼貌的吻别
礼貌的吻别 2020-12-03 02:25

At one point in my code, I created a Set> from a map. Now I want to recreate the same map form, so I want to convert the HashS

6条回答
  •  囚心锁ツ
    2020-12-03 03:24

    These are some toMap utility in common libraries, but unfortunately none of them support Set directly so you need to do Set#toArray() first. (I left out Guava for Neil's answer which is arguably the best)

    Commons Lang's ArrayUtils.toMap

    Map map = ArrayUtils.toMap(entrySet.toArray());
    
    // to recover the type...
    @SuppressWarnings("unchecked")
    Map typedMap = (Map)(Map)map;
    

    Commons Collections' MapUtils.putAll

    Map map = MapUtils.putAll(new HashMap(), entrySet.toArray());
    

    Java 9's Map.ofEntries

     // convert to array and recover the type...
     @SuppressWarnings("unchecked")
     Map map = Map.ofEntries(entrySet.toArray(new Map.Entry[0]));
    
     // You need to copy again if you want a mutable one
     Map hashmap = new HashMap<>(map);
    

提交回复
热议问题