Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

set

map

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?

like image 494
Joeblackdev Avatar asked Apr 19 '13 15:04

Joeblackdev


People also ask

How do you convert an entry to a Map?

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. 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.

What is Map entry in HashMap?

Map.Entry interface in Java with example. HashMap entrySet() Method in Java. Sort an array which contain 1 to n values. Sort 1 to N by swapping adjacent elements.

Can we convert set to Map in Java?

identity() is documented at docs.oracle.com/javase/8/docs/api/java/util/function/… It returns a function that accepts one argument and which returns that argument when called. In the collect example the effect is that the values of the stream of entries are taken as is to construct the map.

How do you add entries to a HashMap?

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.


1 Answers

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.

like image 193
Tagir Valeev Avatar answered Sep 22 '22 17:09

Tagir Valeev