Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java invert map

Tags:

java

map

invert

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?

like image 582
user710818 Avatar asked Aug 22 '11 11:08

user710818


People also ask

How to inverse a map 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.

What is MAP <> in Java?

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.

Can we traverse the map in Java?

In Java 8, you can iterate a map using Map. forEach(action) method and using lambda expression. This technique is clean and fast.


1 Answers

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.

like image 103
dacwe Avatar answered Oct 06 '22 09:10

dacwe