且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-10 22:13:17

如果你的值是唯一的,你可以使用 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.