简体   繁体   中英

Data Structure having same value for multiple keys and searchable by individual keys

I have a use case wherein I have to maintain key-value pair store, all keys are unique and multiple keys can map to a same value. Also it should be searchable by each individual keys.

Eg:

(K1,K2,K3) -> V1
(K3,K4) -> V2
(K5) -> V3

and so on.

Searching on K2 it should return V1

Its somewhat similar to Multikeymap but searchable by individual keys. Is there are any data structure that would allow me to do this in O(1).

There is no such DS which can give results in constant O(1) time but HashMap should be good enough. The average complexity of a hash map is O(1) for insert, delete, and search operations. And if you're using JDK8 , then performance impact of frequent collisions would also be lesser. See: https://dzone.com/articles/hashmap-performance .

Since only the references of the values are stored in the Map, storage should not be a big issue even when there's a mismatch between the number of the keys and values.

And don't forget to override hashcode and equals methods if the key is not Long, String, Int etc. and is some custom object.

If this still does not fulfill your requirements, then check out these links from Guava and Apache Commons Collection libraries but you might have to gather some info about their performance numbers:

  1. https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/keyvalue/MultiKey.html
  2. https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Table.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM