[java] Bi-directional Map in Java?

I have a simple integer-to-string mapping in Java, but I need to be able to easily retrieve string from integer, and also integer from string. I've tried Map, but it can retrieve only string from integer, it's one way:

private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
// This works one way:
String myString = myMap.get(myInteger);

// I would need something like:
Integer myInteger = myMap.getKey(myString);

Is there a right way to do it to have it both directions?

Another problem is that I only have a few constant values that don't change (1->"low", 2->"mid", 3->"high", so it wouldn't be worth to go for a complicated solution.

This question is related to java map guava apache-commons

The answer is


Use Google's BiMap

It is more convenient.


You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:

map.put("theKey", "theValue");
map.put("theValue", "theKey");

Using map.get("theValue") will then return "theKey".

It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:

  • Contains only 1 to 1 pairs
  • Set of values is disjoint from the set of keys (1->2, 2->3 breaks it)

If you want to keep <Integer, String> you could maintain a second <String, Integer> map to "put" the value -> key pairs.


There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.


Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

Apache commons collections has a BidiMap


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to map

Using array map to filter results with if conditional In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? UnmodifiableMap (Java Collections) vs ImmutableMap (Google) Convert JSONObject to Map Convert Map<String,Object> to Map<String,String> iterate through a map in javascript Iterator over HashMap in Java Simple dictionary in C++ Create Map in Java Map with Key as String and Value as List in Groovy

Examples related to guava

UnmodifiableMap (Java Collections) vs ImmutableMap (Google) How to JUnit test that two List<E> contain the same elements in the same order? Bi-directional Map in Java? How can I generate a list or array of sequential integers in Java? initializing a Guava ImmutableMap Interface/enum listing standard mime-type constants builder for HashMap Combine multiple Collections into a single logical Collection? Predicate in Java Map implementation with duplicate keys

Examples related to apache-commons

What does the arrow operator, '->', do in Java? Bi-directional Map in Java? How can I generate a list or array of sequential integers in Java? How can I get an HTTP response body as a string? How can I convert byte size into a human-readable format in Java? Logging framework incompatibility Http Basic Authentication in Java using HttpClient? How to Serialize a list in java? What is the best Java email address validation method?