Find The Closest Answer in HashMap

前端 未结 6 1127
谎友^
谎友^ 2020-12-16 13:07

I want to search for a key in a hashmap and find the nearest one to that key!

    HashMap map = new HashMap();
         


        
6条回答
  •  无人及你
    2020-12-16 13:42

    Iterate over all the keys to find the key with the lowest difference to your target key.

    Here's some code that does that:

    public static Long nearestKey(Map map, Long target) {
        double minDiff = Double.MAX_VALUE;
        Long nearest = null;
        for (long key : map.keySet()) {
            double diff = Math.abs((double) target - (double) key);
            if (diff < minDiff) {
                nearest = key;
                minDiff = diff;
            }
        }
        return nearest;
    }
    

    All that casting to double is to guard against a rollover when target is a large negative and the map key is a large positive

提交回复
热议问题