如果
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();}


