Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

java - Convert Set<Map.Entry<K, V>> to HashMap<K, V>

At one point in my code, I created a Set<Map.Entry<K, V>> from a map. Now I want to recreate the same map form, so I want to convert the HashSet<Map.Entry<K, V>> back into a HashMap<K, V>. Does Java have a native call for doing this, or do I have to loop over the set elements and build the map up manually?

question from:https://stackoverflow.com/questions/16108734/convert-setmap-entryk-v-to-hashmapk-v

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...