Convert Set> to HashMap

后端 未结 6 1341
礼貌的吻别
礼貌的吻别 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:01

    As of Guava 19 you can use ImmutableMap.copyOf(Iterable<Map.Entry<K,V>>)

    0 讨论(0)
  • 2020-12-03 03:03

    Simpler Java-8 solution involving Collectors.toMap:

    Map<Integer, String> mapFromSet = set.stream()
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    

    An IllegalStateException will be thrown if duplicate key is encountered.

    0 讨论(0)
  • 2020-12-03 03:16

    There is no inbuilt API in java for direct conversion between HashSet and HashMap, you need to iterate through set and using Entry fill in map.

    one approach:

    Map<Integer, String> map = new HashMap<Integer, String>();
        //fill in map
        Set<Entry<Integer, String>> set = map.entrySet();
    
        Map<Integer, String> mapFromSet = new HashMap<Integer, String>();
        for(Entry<Integer, String> entry : set)
        {
            mapFromSet.put(entry.getKey(), entry.getValue());
        }
    

    Though what is the purpose here, if you do any changes in Set that will also reflect in Map as set returned by Map.entrySet is backup by Map. See javadoc below:

    Set<Entry<Integer, String>> java.util.Map.entrySet()

    Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

    0 讨论(0)
  • 2020-12-03 03:22

    Fairly short Java 8 solution. Can cope with duplicate keys.

        Map<Integer, String> map = new HashMap<>();
        //fill in map
        Set<Map.Entry<Integer, String>> set = map.entrySet();
        Map<Integer, String> mapFromSet = set.stream().collect(Collectors.toMap(Entry::getKey,
          Entry::getValue,
          (a,b)->b));
    

    Edit: thanks to shmosel who deserves more credit than I do for this

    0 讨论(0)
  • 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<Object, Object> map = ArrayUtils.toMap(entrySet.toArray());
    
    // to recover the type...
    @SuppressWarnings("unchecked")
    Map<K, V> typedMap = (Map<K, V>)(Map<?, ?>)map;
    

    Commons Collections' MapUtils.putAll

    Map<K, V> map = MapUtils.putAll(new HashMap<K, V>(), entrySet.toArray());
    

    Java 9's Map.ofEntries

     // convert to array and recover the type...
     @SuppressWarnings("unchecked")
     Map<K, V> map = Map.ofEntries(entrySet.toArray(new Map.Entry[0]));
    
     // You need to copy again if you want a mutable one
     Map<K, V> hashmap = new HashMap<>(map);
    
    0 讨论(0)
  • 2020-12-03 03:24

    In Java 8 with correct combiner

    Map<Integer, String> map = new HashMap<>();
    //fill in map
    Set<Map.Entry<Integer, String>> set = map.entrySet();
    
    Map<Integer, String> mapFromSet =set.stream().collect(HashMap::new,(t, u) -> t.put(u.getKey(), u.getValue()), 
    (Map mapToReturn, Map otherMap) ->
        {
            otherMap.entrySet().forEach((Map.Entry entry) -> {
                mapToReturn.put(entry.getKey(),entry.getValue());
            });
            return mapToReturn;}););
    
    0 讨论(0)
提交回复
热议问题