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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With