java从hashmap中减去两个值后返回最小差值的键?
从hashmap中减去两个值后,如何返回差异最小的键
范例
first loop -> 10 - 8 = 2;
second loop -> 10 - 9 = 1;
third loop -> 10 - 7 = 3;
therefore second loop -> 10 - 9 = 1 is the smallest, so the key is "Three".
代码
import java.util.HashMap;
public class Difference {
HashMap<String,Double> hashMap = new HashMap<>();
double firstValue = 0;
double secondValue = 0;
double difference = 0;
public Difference() {
hashMap.put("One", 10.0);
hashMap.put("Two", 8.0);
hashMap.put("Three", 9.0);
hashMap.put("Four", 7.0);
firstValue = hashMap.get("One");
for (String key : hashMap.keySet()) {
if(!key.equals("One")) {
secondValue = hashMap.get(key);
difference = Math.abs(secondValue - firstValue);
}
}
}
public static void main(String[] args) {
new Difference();
}
}
请帮忙。谢谢
# 1 楼答案
您可以使用以下方法实现这一点:
# 2 楼答案
尝试使用类似这样的代码:
# 3 楼答案
我认为你的问题比你想象的要简单。我知道这不是最好的,但这里有一个解决方案: