Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best data structure for two way mapping

I want a data structure that maps from key to object and vice-versa(unlike HashMaps that map only in a single direction.) An idea could be to store the HashMap within itself for reverse look-up, but it will be an inefficient approach.

What would be the best implementation for two-way mapping?

like image 254
dev Avatar asked Feb 20 '14 16:02

dev


People also ask

Which data structure is used in map?

The map data type is referred to as an associative array because, like an array, it is a collection of values rather than a single value, as an Int or a String is. Furthermore, each distinct key is associated with a value, resulting in an associative array.

How do you make a two way map?

Show activity on this post. Create a hashmap that maps Object to Object - then you can use the same map to store String -> Integer and Integer -> String. When you add a string/int pair just add it both ways to the same map.

What is the best data structure for mapping multiple keys to the same value?

HashMap will store separate references per key, but they can all point to the same reference.

How can use two map in Javascript?

To merge Maps, use the spread operator (...) to unpack the values of two or more Maps into an array and pass them into the Map() constructor, e.g. new Map([... map1, ... map2]) . The new Map will contain the key-value pairs from all provided Map objects.


1 Answers

Simplest idea: wrapper class which contains 2 maps, second with swapped keys/values. You will keep O(1) complexity and will use only slightly more memory since you will (probably) keep there reference to object.

like image 98
IProblemFactory Avatar answered Sep 20 '22 13:09

IProblemFactory