Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java map implementation that returns the closest contained key

I am looking for a Map implementation that returns the value associated with the requested key, or if not present returns the closest value, higher or lower as requested (along with the actual key, perhaps as a Map.Entry).

For example if the Map contained the following String key/value pairs:
alpha:AYE, beta:BEE, charlie:CEE, delta:DEE
and you ask for "Next higher" for "canada" you would get back charlie:CEE

Of course if you ask for the Next higher or Next lower for "charlie" you would get back charlie:CEE

It should use a comparator, so that if it contains Number keys 1, 2, 3 and I request Next higher for 1.4, it would return the 2 key.

like image 816
Victor Grazi Avatar asked Jan 11 '12 03:01

Victor Grazi


People also ask

Which Java map implementation offers the best performance?

HashMap, being a hashtable-based implementation, internally uses an array-based data structure to organize its elements according to the hash function. HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains(). Therefore, it's significantly faster than a TreeMap.

What does map return if key doesnt exist Java?

If the key is not present in the map, get() returns null. The get() method returns the value almost instantly, even if the map contains 100 million key/value pairs.

Can 2 keys have same value in map?

However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.


1 Answers

Use a NavigableMap: http://docs.oracle.com/javase/6/docs/api/java/util/NavigableMap.html

In particular, use floorEntry or ceilingEntry or a combination.

TreeMap is an instance of NavigableMap, so you can use that: http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html

like image 133
Thomas Eding Avatar answered Oct 05 '22 10:10

Thomas Eding