Bidirectional map

Can you offer some kind of map or similar data structure, where we can get both value and key from each other on an equal basis. That is, everyone can be used to search for others.

+42
java dictionary
Mar 20 '12 at 7:45
source share
7 answers

Java does not have a bi-directional map in its standard library.

Use, for example, BiMap<K, V> from Google Guava .

+30
Mar 20 2018-12-12T00:
source share

If you feel the pain brings some third-party library. How about this simple class.

 public class BiMap<K,V> { HashMap<K,V> map = new HashMap<K, V>(); HashMap<V,K> inversedMap = new HashMap<V, K>(); void put(K k, V v) { map.put(k, v); inversedMap.put(v, k); } V get(K k) { return map.get(k); } K getKey(V v) { return inversedMap.get(v); } } 

Make sure that class K and V have the correct hashCode implementation.

+16
Feb 05 '16 at 8:46
source share

The most common solution is to use two cards. You can easily encapsulate them in a class using a friendly interface by extending AbstractMap . ( Update: This is implemented as a Guava HashBiMap : two maps.)

Creating a new data structure using only arrays and custom classes has several advantages. Map implementations are lightweight wrappers on a data structure that indexes keys. Since you need two indexes, you can use two full maps.

+11
Mar 20 2018-12-12T00:
source share

Also try the Apache Commons Collections 4 BidiMap Package.

+7
May 31 '15 at 16:32
source share

Google Guava contains BiMap (BiDirectional Map).

+5
Mar 20 '12 at 7:52
source share

good for average usecase, where you need such a dictionary, I don’t see anything wrong with the KISS solution, just returned the key and the value on the contrary, saving the overhead of the second card or even the library just for that purpose

 myMap.put("apple", "Apfel"); myMap.put("Apfel", "apple"); 
+1
Mar 21 '16 at 21:29
source share

You can define enum and define a helper method to get the key. Performance is much better compared to BidiMap. for example

 public enum Fruit { APPLE("_apple"); private final String value; Fruit(String value){ this.value=value; } public String getValue(){ return this.value; } public static String getKey(String value){ Fruit fruits[] = Fruit.values(); for(Fruit fruit : fruits){ if(value.equals(fruit.value)){ return fruit.name(); } } return null; } } 
0
Jan 31 '19 at 11:18
source share



All Articles