Java - 按规则从HashMap中获得前15名 [英] Java - get top 15 from HashMap by rule
问题描述
我想请求帮助。假设我有HashMap,其键值如下所示:
String1 0.99
String2 0.98
String3 0.97
String4 0.98
String5 0.5
String6 0.4
String7 0.3
等
我想用这个公式保存前15个条目: Math.abs(value - 0.5)。
这些数据的计算值(按公式计算)为:
String1 0.49
String2 0.48
String3 0.47
String4 0.48
String5 0
String6 0.1
String7 0.2
String1 0.49
String4 0.48
String2 0.48
String3 0.47
String7 0.2
String6 0.1
String5 0
现在我想拥有一个数组,其中索引将是原始值的顺序和值,如下所示:
array [0] = 0.99
array [1] = 0.98
array [2] = 0.98
arra y [3] = 0.97
array [4] = 0.3
array [5] = 0.4
array [6] = 0.5
感谢大家的帮助
任何帮助将不胜感激。谢谢
第一个选项是迭代整个地图并找到您的值 - 可能将其放入数组中并使用O(n * log n)排序算法或15 * O(n)遍历它。
你可以放弃密钥唯一的条件吗?然后使用有序对(String,float)并编写一个客户 Comparator
,它在float值上实现您的规则,并使用 SortedSet
。
可能有涉及 BiMap
的解决方案,我不确定。 / p>
I would like to ask for help. Let's say I have HashMap with key-value like this:
String1 0.99
String2 0.98
String3 0.97
String4 0.98
String5 0.5
String6 0.4
String7 0.3
etc.
And I would like to save to array the top 15 entries by this formula: Math.abs(value - 0.5).
The counted values (by the formula) for this data would be:
String1 0.49
String2 0.48
String3 0.47
String4 0.48
String5 0
String6 0.1
String7 0.2
The values sorted
String1 0.49
String4 0.48
String2 0.48
String3 0.47
String7 0.2
String6 0.1
String5 0
And now I would like to have array, where index would be the order and value the original value, like this:
array[0] = 0.99
array[1] = 0.98
array[2] = 0.98
array[3] = 0.97
array[4] = 0.3
array[5] = 0.4
array[6] = 0.5
Thanks everyone for help
Any help would be appreciated. Thank You
First option is to iterate over the whole map and find your values - perhaps throw it into an array and use an O(n * log n) sort algorithm or 15*O(n) walks over it.
Can you drop the condition that the keys are unique? Then work with ordered pairs (String, float) and write a customer Comparator
that implements your rule on the "float" value, and use a SortedSet
.
There may be a solution involving BiMap
, I'm not sure.
这篇关于Java - 按规则从HashMap中获得前15名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!