Java HashMap find the most suitable key
4 answers
The easiest way
HashMap<Float, String> map = new HashMap<Float, String>();
Float newFloat = 123F;
Float minDif = null;
Float findedValue = null;
for (Float key : map.keySet()) {
Float dif = Math.abs(key - newFloat);
if (minDif != null) {
if (dif < minDif) {
minDif = dif;
findedValue = key;
}
} else {
minDif = dif;
findedValue = key;
}
}
0
source to share