It's a simple question, I have a simple HashMap of which i want to reverse the keys and values.
HashMap<Character, String> myHashMap = new HashMap<Character, String>(); myHashMap.put('a', "test one"); myHashMap.put('b', "test two");
and I want to create a new HashMap in which i put the opposites.
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>(); e.g. Keys "test one" & "test two" and values 'a' & 'b'.
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.
Use Collectors. toMap() method to get the result in another Map. In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator.
To remove all values from HashMap, use the clear() method.
They all are unique, yes
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>(); for(Map.Entry<Character, String> entry : myHashMap.entrySet()){ myNewHashMap.put(entry.getValue(), entry.getKey()); }
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse()
method :
BiMap<Character, String> myBiMap = HashBiMap.create(); myBiMap.put('a', "test one"); myBiMap.put('b', "test two"); BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
As java-8 is out, you can also do it this way :
Map<String, Integer> map = new HashMap<>(); map.put("a",1); map.put("b",2); Map<Integer, String> mapInversed = map.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:
Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();
Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique
org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
Sample code
HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap)
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