Java HashMap find the most suitable key

I have a Java HashMap with floating keys and string values. now a given Float that is not in the HashMap, how can I find the key that most closely resembles a given Float?

+3


source to share


4 answers


Sounds like an assignment for one of the implementations java.util.NavigableMap

.



+8


source


Using floats as keys in a HashMap is a very bad idea!



+1


source


I think you are better off using a simple array / ArrayList

with items sorted by key and execute Collections.binarySearch()

. If no entry is found, it returns the nearest neighbor.

0


source


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







All Articles