简体   繁体   English

给定Float值,在HashMap中找到“最近的Float键”

[英]Find the “closest Float key” in a HashMap given a Float value

Have a LinkedHashMap<Float, Integer> . 有一个LinkedHashMap<Float, Integer> The keys of this HashMap are points in time in seconds (like 0.031f or 1.4021f ). 该HashMap的键是以秒为单位的时间点(例如0.031f1.4021f )。 There can be hundreds of thousands of entries. 可能有成千上万的条目。

Given a float value, say 0.6102f , I need to find the HashMap key that is closest to it (like 0.6002f maybe, assuming that's in the keyset). 给定一个float值,例如0.6102f ,我需要找到最接近它的HashMap键(例如0.6002f ,假设它在键集中)。

A trivial answer would be to check key by key of the HashMap. 一个简单的答案是逐个检查HashMap的密钥。 After all, the entries happen to be correctly sorted. 毕竟,这些条目恰好被正确地排序了。 But I guess that's an O(n) operation which may not be a great idea given that I have to perform this search several times per second. 但是我想这是一个O(n)操作,考虑到我必须每秒执行几次搜索,这可能不是一个好主意。

Is there an efficient way to find the "closest float key" of a HashMap given a float? 有没有一种有效的方法来找到给定浮点数的HashMap的“最接近的浮点数键”?

There is no efficient way to do this using a HashMap ; 没有有效的方法使用HashMap来做到这一点; ie nothing that is better than O(N) where N is the number of entries in the map. 即没有什么比O(N)更好的了,其中N是映射中的条目数。

However, if you switch to using a TreeMap<Float, Integer> you can find the entry with the closest key in O(logN) . 但是,如果切换到使用TreeMap<Float, Integer> ,则可以在O(logN)找到具有最接近键的条目。 You need to use floorEntry and ceilingEntry and then test which of the 2 entry keys is nearest to your given key. 您需要使用floorEntryceilingEntry ,然后测试2个输入键中的哪个最接近您的给定键。


After all, the entries happen to be correctly sorted. 毕竟,这些条目恰好被正确地排序了。

Actually the keys in a HashMap aren't sorted. 实际上, HashMap中的键未排序。 The hashCode() implementations for some key types may make appear that the HashMap keys are sorted, but what you are seeing is an artifact. 某些键类型的hashCode()实现似乎使HashMap键已排序,但您看到的是工件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM