Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find The Closest Answer in HashMap

Tags:

java

hashmap

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

like image 609
Khashayar Avatar asked Feb 28 '12 13:02

Khashayar


1 Answers

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();
}
like image 132
Sergey Kalinichenko Avatar answered Sep 20 '22 15:09

Sergey Kalinichenko