Hi I have a HashMap
and also a function which returns a double value known as answer
. I want to check which value in the Hash
With a HashMap
, you have to go through each entry.
However, if performance is important and you're going to be finding several entries this way, you could create another collection: a list or an array of the entries in the hash map, sorted by value. You could then do a binary search to find the entry with the nearest value more efficiently, and return the key. Of course that doesn't help if you're only going to do this once per map...
If your values are unique, you can use a TreeMap, which implements NavigableMap, which has the nice ceilingKey
and floorKey
methods:
NavigableMap<Double, String> map = new TreeMap<>();
map.put(0d, "A");
map.put(0.25, "B");
map.put(0.5, "C");
map.put(0.75, "D");
map.put(1d, "E");
double value = 0.42;
double above = map.ceilingKey(value);
double below = map.floorKey(value);
System.out.println(value - below > above - value ? above : below); //prints 0.5
Note: both methods can return null if value
is less (resp. greater) than the smallest / largest key.
HashMap isn't the best structure to do this. You can get output.keySet() and check each value, for example:
for(String key:output.keySet()){
Double temp=Math.abs(output.get(key)-answer);
if(temp<min){
min=temp;
nearest=key;
}
}
but it's not the best way. you are forced to use a hashmap? By the way, this isn't a problem if you have always five answer to check...
The concept of 'closest' is not really meaningful for Hashed data structures. The primary goal of efficient hashing algorithms is collision avoidance, which is directly contrary to closeness. Either you have a collision, or not.
If you were asking this for an ordered key data structure (eg. TreeMap
), the answer would be different.