I need a structure <K, V> where I can easily...
# announcements
e
I need a structure <K, V> where I can easily retrieve either the V given K as usually and viceversa. I used a
MutableMap
till now, but it's quite ugly to extract the K given the V (I can loop on the whole
entries
and get the first match). Is there anything better for my case?
s
MutableMaps use hashes of keys to retrieve values in
O(1)
, retrieving keys by value is slower as it needs to search through all keys to get one with a matching value. A list of pairs could do the job, but that would be O(n) both ways
d
Two maps is the easiest way.
Copy code
class BiMap<K, V> {
    val map1: Map<K, V>
    val map2: Map<V, K>
}
g
it's called BiMap and used to be part of Guava. I'd check the implementation. https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap
👍 1
e
nice idea
thanks all, guys