Java - 如何从最接近特定数字的哈希图中找到一个值?

Java - How to find a value from a hashmap that is the closest to a particular number?(Java - 如何从最接近特定数字的哈希图中找到一个值?)
本文介绍了Java - 如何从最接近特定数字的哈希图中找到一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

您好,我有一个 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,它有很好的 ceilingKeyfloorKey 方法:

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 - 如何从最接近特定数字的哈希图中找到一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)