Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have a HashMap with reverse lookup?

I have data that is organized in kind of a "key-key" format, rather than "key-value". It's like a HashMap, but I will need O(1) lookup in both directions. Is there a name for this type of data structure, and is anything like this included in Java's standard libraries? (or maybe Apache Commons?)

I could write my own class that basically uses two mirrored Maps, but I'd rather not reinvent the wheel (if this already exists but I'm just not searching for the right term).

like image 326
Kip Avatar asked Nov 03 '09 20:11

Kip


People also ask

Can we reverse HashMap in Java?

We can reverse the elements in the linked hash map by first reversing the elements. After reversing, we can iterate it. This method is used to reverse the elements or mappings order in the LinkedHashMap.

How can we create a map with reverse view and lookup 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 the best alternative for HashMap in Java?

Whereas, ConcurrentHashMap is introduced as an alternative to the HashMap. The ConcurrentHashMap is a synchronized collection class. The HashMap is non-thread-safe and can not be used in a Concurrent multi-threaded environment.

What is HashMap lookup?

A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.


1 Answers

There is no such class in the Java API. The Apache Commons class you want is going to be one of the implementations of BidiMap.

As a mathematician, I would call this kind of structure a bijection.

like image 77
uckelman Avatar answered Sep 20 '22 18:09

uckelman