Reverse HashMap keys and values in Java

how to reverse hashmap in java
how to reverse linkedhashmap in java
hashmap java
java hashmap by value
sort hashmap by value java 8
java hashmap get key from value
java bidirectional map
how to reverse a treemap in java

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

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();

Java invert map, Java 8: public static <V, K> Map<V, K> invert(Map<K, V> map) { return map. If it is not null you may throw a new IllegalArgumentException("Map values must be Map<Integer, String> map = new HashMap<>(); map.put(1, "one"); map.put(2, of "c" style checks and allows you to display all the original keys and values. To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value. But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as

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) 

Sort Map in Java by Reverse Ordering of its keys, Below are the steps: Obtain stream from Set view of the mappings contained in the map. Sort the stream in reverse order of keys using Stream. sorted() method. Construct a LinkedHashMap from the stream using Stream. collect() with Collectors. toMap() . Using forEach() method: forEach() is a method of hashmap which is introduced in java 8. It is used to iterate through the hashmap and also reduces the number of lines of code. It is used to iterate through the hashmap and also reduces the number of lines of code.

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

How to get Key From Value in Hashtable, HashMap or , , you can sort the keys based on the logic provided inside the compare method. HashMap replace(key, value) method in Java with Examples The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value.

I wrote a simpler loop that works too (note that all my values are unique):

HashMap<Character, String> myHashMap = new HashMap<Character, String>();
HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();

for (char i : myHashMap.keySet()) {
    reversedHashMap.put(myHashMap.get(i), i);
}

How to reverse sorted keys in a TreeMap?, When I iterate over a HashMap in Java, and print the entries in it, why is the order in HashMap does not have a concept of ordering, so the reverse operation  Java HashMap tutorial: HashMap in java HashMap internal working hash and indexfor method in HashMap hashcode and equals in java sort HashMap by keys and values Difference between HashMap and HashSet Difference between HashMap and Hashtable How to iterate over HashMap Sorting by Keys: Sorting by keys can be easily done using TreeMap.

To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.

But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.

How to reverse the values of HashMap, Learn how to retrieve a key from a Java Map given the value. inverse() to get the value-key Map or the reverse Map to fetch the key based on  It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It does not sort the stored keys and Values. You must need to import java.util.HashMap or its super class in order to use the HashMap class and methods. HashMap Example in Java:

Get the Key for a Value from a Java Map, Iterating in reverse order means fetching last element of the map first, second last and fetch element at that position but unfortunately java.util. we easily get the value corresponding to the key from the map. static void methodOne() { Map<​String, String> map = new LinkedHashMap<String, String>();  Maps are not like lists, which can be reversed by swapping head with tail. Objects in maps have a computed position, and using the value as key and the key as value would requiere to re-compute the storage place, essentialy building another map. There is no elegant way. There are, however, bidirectional maps.

How to iterate Map in reverse order, containsKey(): java.util.HashMap.containsKey() It returns true if this map maps one or more keys to the specified value. Syntax: public boolean containsValue(  Java HashMap is a hash table based implementation of Java’s Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values. Following are few key points to note about HashMaps in Java - A HashMap cannot contain duplicate keys. Java HashMap allows null values and the null key.

Hashmap methods in Java with Examples, By default, all key-value pairs in TreeMap are sorted in their natural order. So all you need to To reverse sort map entries, pass Collections.reverseOrder() in  In this article, we will discuss how to sort HashMap by its Keys and Values using stream in Java 8. Prior to Java 8 release, we can sort HashMap either by its Keys or Values as explained in the below articles, With the release of Java 8, we can use sorted () method of Stream class by passing comparator objects.

Comments
  • Simple question, simple answer. Can you tell us where you got stuck?
  • First of all you have to be sure that your values are unique. Otherwise, it should be Map<String, List<Character>>
  • well, I'm fairly new to JAVA and wouldn't know where to start...
  • They all are unique, yes
  • This is not always possible to do without losing data. Imagine you have this: a -> test one; b -> test two; c -> test one (in your first map). What will you get in your second (output) map? Something like this: test one -> a (or c); test two -> b. So 1st map has 3 entries, 2nd map has just 2.
  • Thanks for explanation of Bi-Directional map usage. I didn't know that and it is really useful for me!
  • When I use your java-8 method with the collectors, I get the following error on Map.Entry::getValue and getKey: Non-static method cannot be referenced from a static context
  • Jan, it's because your map is of a different generic type than declared with the the mapInversed variable.
  • what if values are duplicate ? how do you handle that ?
  • @ChaitanyaUttarwar You'd have to find a merging strategy to map the different keys that are associated with the same value in your original map (you could group them into a list, sum them, take only one key depending on what you want to achieve).
  • entrySet is better, the hash code has not to be computed on each get
  • @A4L That's true, but for simple tasks there's not much of a difference.
  • I think a note about how duplicate values becoming keys will be handled would be useful.
  • @CHBuckingham agreed