HashMap selections = new HashMap<Integer, Float>();
How can i get the Integer key of the 3rd smaller value of Float in all 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()));
}
}
}
i need the runner of the 3rd smaller price with depth 1
maybe i should implement this in another way?
Michael Mrozek nails it with his question if you’re using
HashMapright: this is highly atypical scenario forHashMap. That said, you can do something like this:Set<Map.Entry<K,V>>from theHashMap<K,V>.entrySet().addAlltoList<Map.Entry<K,V>>Collections.sortthe list with a customComparator<Map.Entry<K,V>>that sorts based onV.Map.Entry<K,V>only, then aO(N)selection algorithm may suffice.//after edit
It looks like
selectionshould really be aSortedMap<Float, InflatedRunner>. You should look atjava.util.TreeMap.Here’s an example of how
TreeMapcan be used to get the 3rd lowest key:Also note how I take advantage of Java’s auto-boxing/unboxing feature between
intandInteger. I noticed that you usednew Integerandnew Floatin your original code; this is unnecessary.//another edit
It should be noted that if you have multiple
InflatedRunnerwith 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<Float,Set<InflatedRunner>>MultiMapfrom Google CollectionsList<RunnerPricePair>(sorry, I’m not familiar with the domain to name it appropriately), whereRunnerPricePair implementsComparable<RunnerPricePair>that compares on prices. You can just add all the pairs to the list, then either:Collections.sortthe list and get the 3rd pair