問題描述
您好,我有一個 HashMap<String, Double>
以及一個返回雙精度值的函數,稱為 answer
.我想檢查 HashMap 中的哪個值最接近答案,然后獲取該值的鍵并打印它.
Hi I have a HashMap<String, Double>
and also a function which returns a double value known as answer
. I want to check which value in the HashMap is the closest to the answer and then grab that value's key and print it.
HashMap<String, Double> output = new HashMap<String, Double>();
contents
("A", 0)
("B", 0.25)
("C", 0.5)
("D", 0.75)
("E", 1)
假設我的一個函數的答案是 0.42,我如何檢查它最接近哪個值,然后獲取該值的鍵.我無法切換 HashMap 的鍵和值(因為之前的函數將值平均分配給每個字母),否則最好遍歷每個鍵并獲取值.
Suppose the answer to one of my functions was 0.42, how can I check which value it is closest to and then grab the key to that value. I cant switch around the key and value of the HashMap (as a previous function assigns the values equally to each letter), otherwise it would be better to go through each key and get the value.
推薦答案
如果你的值是唯一的,你可以使用 TreeMap,實現 NavigableMap,它有很好的 ceilingKey
和 floorKey
方法:
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
注意:如果 value
小于(或大于)最小/最大鍵,則兩種方法都可以返回 null.
Note: both methods can return null if value
is less (resp. greater) than the smallest / largest key.
這篇關于Java - 如何從最接近特定數字的哈希圖中找到一個值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!