简体   繁体   中英

fast static key-value mapping

I have a set of unique key-value pairs, both key and value are strings. The number of pairs is very huge and finding the value of a certain string is extremely time-critical.

The pairs are computed beforehand and are given for a certain program. So i could just write a method containing:

public String getValue(String key)
{
    //repeat for every pair
    if(key.equals("abc"))
    {
        return "def";
    }
}

but i am talking about more than 250,000 pairs and perhaps sorting them could be faster...

I am having a class that contains the getValue() method and can use its constructor, but has no connection to any database/file system etc. So every pair has to be defined inside the class.

Do you have any ideas that could be faster than a huge series of if-statements? Perhaps using a sorting map that gets the pairs presorted. Perhaps improve constructor-time by deserializing an already created map?

I would like your answers to contain a basic code example of your approach, I will comment answers with their corresponding time it took an a set of pairs!

Time-frame: for one constructor call and 20 calls of getValue() 1000 milliseconds.

Keys have a size of 256 and values have a size < 16

This is exactly what a hash table is made for. It provides O(1) lookup if implemented correctly, which means that as long as you have enough memory and your hash function and collision strategy are smart, it can get values for keys in constant time. Java has multiple hash-backed data structures, from the sounds of things a HashMap<String, String> would do the trick for you.

You can construct it like this:

 Map<String, String> myHashTable = new HashMap<String, String>();

add values like this:

 myHashTable.put("abcd","value corresponding to abcd");

and get the value for a key like this:

myHashTable.get("abcd");

You were on the right track when you had the intuition that running through all of the keys and checking was not efficient, that would be an O(n) runtime approach, since you'd have to run through all n elements.

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