I want to search for a key in a hashmap and find the nearest one to that key!
HashMap map = new HashMap();
Iterate over all the keys to find the key with the lowest difference to your target key.
Here's some code that does that:
public static Long nearestKey(Map map, Long target) {
double minDiff = Double.MAX_VALUE;
Long nearest = null;
for (long key : map.keySet()) {
double diff = Math.abs((double) target - (double) key);
if (diff < minDiff) {
nearest = key;
minDiff = diff;
}
}
return nearest;
}
All that casting to double is to guard against a rollover when target is a large negative and the map key is a large positive