HashMap selections = new HashMap<Integer, Float>();
我怎样才能获得的浮动的第三小值在所有的HashMap的整数键?
How can i get the Integer key of the 3rd smaller value of Float in all HashMap?
修改 即时通讯使用HashMap的这种
Edit im using the HashMap for this
for (InflatedRunner runner : prices.getRunners()) {
for (InflatedMarketPrices.InflatedPrice price : runner.getLayPrices()) {
if (price.getDepth() == 1) {
selections.put(new Integer(runner.getSelectionId()), new Float(price.getPrice()));
}
}
}
我需要的第三个较小的代价亚军与深度1
i need the runner of the 3rd smaller price with depth 1
也许我应该以另一种方式实现这一点?
maybe i should implement this in another way?
如果您使用的是迈克尔Mrozek指甲用他的问题的HashMap
右:这是非常典型的场景为的HashMap
。这就是说,你可以做这样的事情:
Michael Mrozek nails it with his question if you're using HashMap
right: this is highly atypical scenario for HashMap
. That said, you can do something like this:
设置&LT;为Map.Entry&LT; K,V&GT;&GT;
从的HashMap&LT; K,V&GT; .entrySet()
。
的addAll
到名单,其中,为Map.Entry&LT; K,V&GT;&GT;
Collections.sort
列表中使用自定义比较&LT;为Map.Entry&LT; K,V&GT;&GT;
的根据 V
排序。
如果您只需要3 的Map.Entry&LT; K,V&GT;
只,那么 O(N)
选择算法就足够了。
get the Set<Map.Entry<K,V>>
from the HashMap<K,V>.entrySet()
.
addAll
to List<Map.Entry<K,V>>
Collections.sort
the list with a custom Comparator<Map.Entry<K,V>>
that sorts based on V
.
If you just need the 3rd Map.Entry<K,V>
only, then a O(N)
selection algorithm may suffice.
//修改后的
看起来选择
应该是一个真正的SortedMap&LT;浮动,InflatedRunner&GT;
。你应该看看 的java.util .TreeMap
。
It looks like selection
should really be a SortedMap<Float, InflatedRunner>
. You should look at java.util.TreeMap
.
下面是一个例子,说明 TreeMap的
可以用来取得第三个最关键的:
Here's an example of how TreeMap
can be used to get the 3rd lowest key:
TreeMap<Integer,String> map = new TreeMap<Integer,String>();
map.put(33, "Three");
map.put(44, "Four");
map.put(11, "One");
map.put(22, "Two");
int thirdKey = map.higherKey(map.higherKey(map.firstKey()));
System.out.println(thirdKey); // prints "33"
另外请注意我是如何走的 INT
和整数
利用Java的自动装箱/拆箱功能。我注意到,你使用新的整数
和新的浮动
在你原来的code;这是不必要的。
Also note how I take advantage of Java's auto-boxing/unboxing feature between int
and Integer
. I noticed that you used new Integer
and new Float
in your original code; this is unnecessary.
//另一个修改
应该注意的是,如果你有多个 InflatedRunner
与同价位的,只有一个会被保留。如果这是一个问题,你需要保留的所有运动员,那么你可以做的几件事情之一:
It should be noted that if you have multiple InflatedRunner
with the same price, only one will be kept. If this is a problem, and you want to keep all runners, then you can do one of a few things:
TreeMap的&LT;浮动,设置&LT; InflatedRunner&GT;&GT;
使用 Multimap之
从谷歌集合
If you really need a multi-map (one key can map to multiple values), then you can:
have TreeMap<Float,Set<InflatedRunner>>
Use MultiMap
from Google Collections
Collections.sort
的列表,并获得在第三对
使用O(N)选择算法
Collections.sort
the list and get the 3rd pair
Use O(N) selection algorithm