在 HashMap 中找到最接近的答案 [英] Find The Closest Answer in HashMap
本文介绍了在 HashMap 中找到最接近的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 hashmap 中搜索一个键并找到离该键最近的一个!
I want to search for a key in a hashmap and find the nearest one to that key!
HashMap<Long, Object> map = new HashMap<Long , Object>();
所以基本上我想搜索一个 long,如果它在地图中不存在,则找到与该 long 值最接近的匹配!我该怎么做!?
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!?
提前感谢
推荐答案
你不能用 HashMap
来完成它而不迭代它的所有键.我认为这不是您所追求的,所以这是一种使用 TreeMap
的方法:
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();
}
这篇关于在 HashMap 中找到最接近的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文