Java - How to find a value from a hashmap that is the closest to a particular number?

后端 未结 4 1672
北荒
北荒 2021-01-14 07:44

Hi I have a HashMap and also a function which returns a double value known as answer. I want to check which value in the Hash

4条回答
  •  天命终不由人
    2021-01-14 07:56

    If your values are unique, you can use a TreeMap, which implements NavigableMap, which has the nice ceilingKey and floorKey methods:

        NavigableMap 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
    

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

提交回复
热议问题