Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse HashMap keys and values in Java

Tags:

java

hashmap

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'. 
like image 315
Ken Avatar asked Dec 05 '13 22:12

Ken


People also ask

How do you reverse a HashMap in Java?

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.

How do you sort a HashMap in reverse order?

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.

How remove all keys and values from HashMap in Java?

To remove all values from HashMap, use the clear() method.


2 Answers

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(); 
like image 119
Alexis C. Avatar answered Sep 20 '22 23:09

Alexis C.


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)  
like image 41
Riju Thomas Avatar answered Sep 20 '22 23:09

Riju Thomas