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?
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.
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.
HashMap will store separate references per key, but they can all point to the same reference.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With