我想在 HashMap 中搜索一个键并找到离该键最近的一个!
HashMap<Long, Object> map = new HashMap<Long , Object>();
所以基本上我想搜索一个 long,如果它不存在于 map 中,找到最接近该 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();
}
关于java - 在 HashMap 中找到最接近的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9482988/