开发者

how to get the lowest float value from the hash map

开发者 https://www.devze.com 2023-04-11 02:07 出处:网络
I have a map which looks like below. What I want to do is get the minimum float valu开发者_如何学Ce and its corresponding key. Also the float values are like for example 3127668.8 or 1.786453E7 and so

I have a map which looks like below. What I want to do is get the minimum float valu开发者_如何学Ce and its corresponding key. Also the float values are like for example 3127668.8 or 1.786453E7 and so on and so forth. How can I achieve this?

Map<String, Float> distance = new HashMap<String, Float>();


String str;
Float min =Float.valueOf(Float.POSITIVE_INFINITY );
for(Map.Entry<String,Float> e:distance.entrySet()){
    if(min.compareTo(e.getValue())>0){
        str=e.getKey();
        min=e.getValue();
    }
}


One line of code:

Float min = Collections.min(distance.values());

It's easy to maintain by JDK library.


Iterate over the entries and do a comparison.

Alternatively, use a wrapper class that does the comparison on item entry to avoid the iteration, or a map implementation that does sorting/ordering based on arbitrary criteria, etc.


try this:

String minKey = null;
Float minValue = Float.MAX_VALUE;
for (Map.Entry<String, Float> entry : distance.entrySet()) {
    Float value = entry.getValue();
    if (value < minValue) {
        minKey = entry.getKey();
        minValue = value;
    }
}


You can iterate over the entry set of the map, i.e., distance.entrySet(), which is a collection of Map.Entry objects, which are basically a key/value pair. Something like this:

Map.Entry<String,Float> minEntry;
for(entry : distance.entrySet()) {
    if(minEntry == null) {
        minEntry = entry;
        continue;
    }
    if(minEntry.getValue() > entry.getValue()) {
        minEntry = entry;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号