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

I am looking for an implementation of a map that returns the value associated with the requested key, or if not, returns the closest value, higher or lower on request (along with the actual key, possibly like Map.Entry).

For example, if the map contained the following key / value pairs of String:
alpha: AYE, beta: BEE, charlie: CEE, delta: DEE
and you ask for "Next higher" for "canada", you will go back to charlie: CEE

Of course, if you ask for "Next Above" or "Next Below" for "charlie", you will go back to charlie: CEE

It should use a comparator, so if it puts the numeric keys 1, 2, 3 and I request Next above for 1.4, it will return the key 2.

+5
source share
1 answer

Use the navigation map: 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 it: http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html

+11
source

All Articles