爪哇 - 如何找到一个HashMap是最接近于一个特定的数字的值? [英] Java - How to find a value from a hashmap that is the closest to a particular number?

查看:428
本文介绍了爪哇 - 如何找到一个HashMap是最接近于一个特定的数字的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个的HashMap<弦乐,双> ,并返回称为答案双重值的函数。我想检查哪些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中的键和值开关(为previous功能同样分配值,每个字母),否则倒不如去通过每一个键,得到的值。

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

请注意:这两种方法可以返回null如果小于最小/最大键

Note: both methods can return null if value is less (resp. greater) than the smallest / largest key.

这篇关于爪哇 - 如何找到一个HashMap是最接近于一个特定的数字的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆