在HashMap中查找最接近的答案 [英] Find The Closest Answer in HashMap
本文介绍了在HashMap中查找最接近的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap< Long,对象> map = new HashMap< Long,Object>();
所以基本上我想搜索一个很长的,如果它不存在于地图上,找到最接近匹配的长期价值!
我该怎么做!
提前发送
解决方案
不能用 HashMap
来完成,而不必遍历所有的键。我认为这不是你所追求的,所以这里用一个 TreeMap
来实现:
TreeMap的<长,对象> map = new TreeMap< Long,Object>();
长键= 42;
Map.Entry< Long,Object> low = map.floorEntry(key);
Map.Entry< Long,Object> high = map.ceilingEntry(key);
Object res = null; (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();
}
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>();
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
解决方案
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屋!
查看全文