I want to search for a key in a hashmap and find the nearest one to that key!
HashMap<Long, Object> map = new HashMap<Long , Object>();
so basically I want to search for a long and if it didn't exist in the map find the nearest match to that long value! How can I do that!?
Thanx in advance
You cannot do it with HashMap
without iterating over all of its keys. I assume that this is not what you are after, so here is a way do it with a TreeMap
:
TreeMap<Long,Object> map = new TreeMap<Long,Object>();
Long key = 42;
Map.Entry<Long,Object> low = map.floorEntry(key);
Map.Entry<Long,Object> high = map.ceilingEntry(key);
Object res = null;
if (low != null && high != null) {
res = Math.abs(key-low.getKey()) < Math.abs(key-high.getKey())
? low.getValue()
: high.getValue();
} else if (low != null || high != null) {
res = low != null ? low.getValue() : high.getValue();
}
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