简体   繁体   English

在HashMap中找到最接近的答案

[英]Find The Closest Answer in HashMap

I want to search for a key in a hashmap and find the nearest one to that key! 我想在hashmap中搜索一个键,找到离该键最近的一个键!

    HashMap<Long, Object> map = new HashMap<Long , Object>();

so basically I want to search for a long and if it didn't exist in the map find the nearest match to that long value! 所以基本上我想搜索一个长的,如果它在地图中不存在,找到最接近的那个长值! How can I do that!? 我怎样才能做到这一点!?

Thanx in advance Thanx提前

You cannot do it with HashMap without iterating over all of its keys. 如果不迭代所有键,就无法使用HashMap I assume that this is not what you are after, so here is a way do it with a TreeMap : 我假设这不是你想要的,所以这是一个使用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();
}

Using a NavigableMap like a TreeMap 像TreeMap一样使用NavigableMap

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;

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 当目标是一个大的负数并且地图键是一个大的正数时,所有转换为double是防止翻转

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. 如果要按排序顺序将值插入hashMap,则可以使用LinkedHashMap,以便可以维护插入顺序。

  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. 如果对所有键的迭代进行了n次比较,则二进制搜索将使用log(n)进行基数2比较。

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. 我们可以说链接的哈希映射减少了哈希映射的排序中的混乱,而不会导致树映射的性能损失。

Hashes (including HashMap) have no ordering (implement 'Comparable'), they just work with the implementations of equals() and hashCode(). 散列(包括HashMap)没有排序(实现'Comparable'),它们只使用equals()和hashCode()的实现。

In other words, it can not be done. 换句话说,它无法完成。 You may try with an ordered list or set. 您可以尝试使用有序列表或集。

Not? 不? That's not how the get function is supposed to work. 这不是get函数应该如何工作的。 I guess you might be able to use a TreeMap and use the getHeadMap/getTailMap and use some logic to find the closest match. 我猜你可以使用TreeMap并使用getHeadMap / getTailMap并使用一些逻辑来找到最接近的匹配。 But that would probably require to fiddle around a bit. 但这可能需要摆弄一下。 After all what would the closest imply? 毕竟最接近的意味着什么呢? ... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM