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.
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.
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.
I have searched on the Map interface methods but there is no method that takes an entry and puts it in the map. Therefore I have implemented it by myself using a little bit of inheritance and Java 8 interfaces.
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Maps {
// Test method
public static void main(String[] args) {
Map.Entry<String, String> entry1 = newEntry("Key1", "Value1");
Map.Entry<String, String> entry2 = newEntry("Key2", "Value2");
System.out.println("HashMap");
MyMap<String, String> hashMap = new MyHashMap<>();
hashMap.put(entry1);
hashMap.put(entry2);
for (String key : hashMap.keySet()) {
System.out.println(key + " = " + hashMap.get(key));
}
System.out.println("\nTreeMap");
MyMap<String, String> treeMap = new MyTreeMap<>();
treeMap.put(entry1);
treeMap.put(entry2);
for (String key : treeMap.keySet()) {
System.out.println(key + " = " + treeMap.get(key));
}
}
/**
* Creates a new Entry object given a key-value pair.
* This is just a helper method for concisely creating a new Entry.
* @param key key of the entry
* @param value value of the entry
*
* @return the Entry object containing the given key-value pair
*/
private static <K,V> Map.Entry<K,V> newEntry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
/**
* An enhanced Map interface.
*/
public static interface MyMap<K,V> extends Map<K,V> {
/**
* Puts a whole entry containing a key-value pair to the map.
* @param entry
*/
public default V put(Entry<K,V> entry) {
return put(entry.getKey(), entry.getValue());
}
}
/**
* An enhanced HashMap class.
*/
public static class MyHashMap<K,V> extends HashMap<K,V> implements MyMap<K,V> {}
/**
* An enhanced TreeMap class.
*/
public static class MyTreeMap<K,V> extends TreeMap<K,V> implements MyMap<K,V> {}
}
The MyMap interface is just an interface that extends the Map interface
by adding one more method, the public default V put(Entry<K,V> entry).
Apart from just defining the method, a default implementation is coded
too. Doing that, we can now add this method to any class that implements
the Map interface just by defining a new class that implements the
MyMap interface and extending the map implementation class of our choice. All
of that in one line! This is demonstrated in the bottom of the code above where two
classes are created each extending the HashMap and the TreeMap
implementations.
To instantiate a Map with Entries (in the same way as you can do Arrays.asList(T... a) or Sets.newHashSet(T... a) in Google Guava library, I found this:
import java.util.AbstractMap;
import java.util.Map;
public class MapWithEntries {
private static final Map.Entry<String, String> ENTRY_1 = new AbstractMap.SimpleEntry<>("A", "Hello");
private static final Map.Entry<String, String> ENTRY_2 = new AbstractMap.SimpleEntry<>("B", "World");
private static final Map<String, String> MAP_WITH_ENTRIES = Map.ofEntries(ENTRY_1, ENTRY_2);
}
Map.Entry is a key and its value combined into one class. This allows you to iterate over Map.entrySet() instead of having to iterate over Map.keySet(), then getting the value for each key. A better way to write what you have is:
for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
String key = entry.getKey();
JButton value = entry.getValue();
this.add(value);
}
If this wasn't clear let me know and I'll amend my answer.
Note that you can also create your own structures using a Map.Entry as the main type, using its basic implementation AbstractMap.SimpleEntry. For instance, if you wanted to have an ordered list of entries, you could write:
List<Map.Entry<String, Integer>> entries = new ArrayList<>();
entries.add(new AbstractMap.SimpleEntry<String, Integer>(myStringValue, myIntValue));
And so on. From there, you have a list of tuples. Very useful when you want ordered tuples and a basic Map is a no-go.