Java – how do I find a value from the HashMap closest to a specific number?

Hi, I have a HashMap < < string, double >, and a function that returns a double value called the answer I want to check which value in the HashMap is closest to the answer, and then get the key of the value and print it out

HashMap<String,Double> output = new HashMap<String,Double>();


contents
("A",0)
("B",0.25)
("C",0.5)
("D",0.75)
("E",1)

Suppose the answer to one of my functions is 0.42, how do I check its closest value and get the key of that value I can't switch the key and value of HashMap (because the previous function assigns the value to each letter), otherwise I'd better go through each key and get the value

Solution

If your value is unique, you can use treemap, which implements navigablemap and has nice ceilingkey and floatkey 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: if value is less than (max), both methods can return null instead of the min / max key

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>