Find The Closest Answer in HashMap

前端 未结 6 1108
谎友^
谎友^ 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:34

    Using a NavigableMap like a TreeMap

    long key = 
    NavigableMap<Long, Object> map = new TreeMap<Long , Object>();
    
    Long before = map.floorKey(key);
    Long after = map.ceilingKey(key);
    if (before == null) return after;
    if (after == null) return before;
    return (key - before < after - key 
           || after - key < 0) 
           && key - before > 0 ? before : after;
    
    0 讨论(0)
  • 2020-12-16 13:35

    Hashes (including HashMap) have no ordering (implement 'Comparable'), they just work with the implementations of equals() and hashCode().

    In other words, it can not be done. You may try with an ordered list or set.

    0 讨论(0)
  • 2020-12-16 13:37

    You cannot do it with HashMap without iterating over all of its keys. I assume that this is not what you are after, so here is a way do it with a TreeMap:

    TreeMap<Long,Object> map = new TreeMap<Long,Object>();
    Long key = 42;
    Map.Entry<Long,Object> low = map.floorEntry(key);
    Map.Entry<Long,Object> high = map.ceilingEntry(key);
    Object res = null;
    if (low != null && high != null) {
        res = Math.abs(key-low.getKey()) < Math.abs(key-high.getKey())
        ?   low.getValue()
        :   high.getValue();
    } else if (low != null || high != null) {
        res = low != null ? low.getValue() : high.getValue();
    }
    
    0 讨论(0)
  • 2020-12-16 13:38

    Solution :

    1. If you are inserting values into the hashMap in a sorted order you could use a LinkedHashMap so that the insertion order can be maintained.

    2. Now we can perform a binary search over the keys instead of iterating over all keys (like in some of the other answers).

    3. If iteration over all keys took n comparisons, binary search would take log(n)with base 2 comparisons.

    The point to note here would be that this works only if the map is sorted.

    Comparison of diff maps :

    • A hash map is good as a general purpose map implementation that provides rapid storage and retrieval operations. However, it falls short because of its chaotic and unorderly arrangement of entries.

      This causes it to perform poorly in scenarios where there is a lot of iteration as the entire capacity of the underlying array affects traversal other than just the number of entries.

    • A linked hash map possesses the good attributes of hash maps and adds order to the entries. It performs better where there is a lot of iteration because only the number of entries is taken into account regardless of capacity.
    • A tree map takes ordering to the next level by providing complete control over how the keys should be sorted. On the flip side, it offers worse general performance than the other two alternatives.

    We could say a linked hash map reduces the chaos in the ordering of a hash map without incurring the performance penalty of a tree map.

    0 讨论(0)
  • 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<Long, Object> 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

    0 讨论(0)
  • 2020-12-16 13:44

    Not? That's not how the get function is supposed to work. I guess you might be able to use a TreeMap and use the getHeadMap/getTailMap and use some logic to find the closest match. But that would probably require to fiddle around a bit. After all what would the closest imply? ...

    0 讨论(0)
提交回复
热议问题