在HashMap中找到最接近的答案


问题内容

我想在哈希图中搜索键,然后找到与该键最接近的键!

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

因此,基本上我想搜索一个long,如果地图中不存在该long,则找到与该long值最接近的匹配项!我怎样才能做到这一点!?

提前感谢


问题答案:

如果HashMap不迭代其所有键,就无法做到这一点。我假设这不是您想要的,所以这是一种使用的方法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();
}