I need create inverse map - select unique values and for them find keys. Seems that only way is to iterate all key/value pairs, because entrySet returns set of <key,value> so value not unique?
You can use a simple for loop to create a reverse map. The idea is to create a new instance of Map<V,K> for a given map of type Map<K,V> . Then use a loop to iterate over the entries of the given map, and insert each entry into the new map in reverse order of its key-value pair.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.
In Java 8, you can iterate a map using Map. forEach(action) method and using lambda expression. This technique is clean and fast.
The values in a map may not be unique. But if they are (in your case) you can do as you wrote in your question and create a generic method to convert it:
private static <V, K> Map<V, K> invert(Map<K, V> map) { Map<V, K> inv = new HashMap<V, K>(); for (Entry<K, V> entry : map.entrySet()) inv.put(entry.getValue(), entry.getKey()); return inv; }
Java 8:
public static <V, K> Map<V, K> invert(Map<K, V> map) { return map.entrySet() .stream() .collect(Collectors.toMap(Entry::getValue, Entry::getKey)); }
Example of usage:
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("Hello", 0); map.put("World!", 1); Map<Integer, String> inv = invert(map); System.out.println(inv); // outputs something like "{0=Hello, 1=World!}" }
Side note: the put(.., ..)
method will return the the "old" value for a key. If it is not null you may throw a new IllegalArgumentException("Map values must be unique")
or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With