Dan*_*iel 5 java algorithm hashmap
HashMap selections = new HashMap<Integer, Float>();
Run Code Online (Sandbox Code Playgroud)
如何在所有HashMap中获取Float的第3个较小值的Integer键?
为此使用HashMap 编辑即时消息
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()));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要第3个较小价格的跑步者,深度为1
也许我应该以另一种方式实现这一点?
迈克尔·莫兹克(Michael Mrozek)用他的问题指出它,如果你HashMap正确使用的话:这是非常不典型的场景HashMap.也就是说,你可以这样做:
Set<Map.Entry<K,V>>了HashMap<K,V>.entrySet().addAll 至 List<Map.Entry<K,V>>Collections.sort具有Comparator<Map.Entry<K,V>>基于的排序的自定义列表V.
Map.Entry<K,V>,那么O(N) 选择算法就足够了.//编辑后
它看起来selection应该真的是一个SortedMap<Float, InflatedRunner>.你应该看看java.util.TreeMap.
以下是如何TreeMap使用获得第3个最低密钥的示例:
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"
Run Code Online (Sandbox Code Playgroud)
另外请注意我是如何利用之间Java的自动装箱/拆箱功能int和Integer.我注意到,你使用new Integer,并new Float在原来的代码; 这是不必要的.
//另一个编辑
应该注意的是,如果您有多个InflatedRunner具有相同价格,则只保留一个.如果这是一个问题,并且您希望保留所有跑步者,那么您可以执行以下操作之一:
TreeMap<Float,Set<InflatedRunner>>MultiMap来自谷歌集合List<RunnerPricePair>(对不起,我不熟悉域名来恰当地命名),在那里RunnerPricePair implements Comparable<RunnerPricePair>比较价格.您可以将所有对添加到列表中,然后执行以下任一操作:
Collections.sort 列表并获得第3对