4

I have a map which looks like below. What I want to do is get the minimum float value 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>();
SASM
  • 1,292
  • 1
  • 22
  • 44

5 Answers5

8
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();
    }
}
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • @SHiRKiT it's the best you can get without a redesign – ratchet freak Oct 06 '11 at 21:43
  • I would only change the default value of min to `Float.MAX_VALUE`, but just because I don't know the uses nor the value of `Float.POSITIVE_INFINITY`. – SHiRKiT Oct 06 '11 at 22:07
  • @SHiRKiT [Float.compareTo](http://download.oracle.com/javase/6/docs/api/java/lang/Float.html#compareTo(java.lang.Float)) has positive infinity as larger than any representable number (check the [IEEE standard](http://en.wikipedia.org/wiki/Floating_point#Infinities) ) but any number guaranteed to be larger than the smallest is fine I just went to the extreme – ratchet freak Oct 06 '11 at 22:13
  • it just prints infinity and null – SASM Oct 06 '11 at 22:17
  • 1
    @Suyesh reverse the comparison (`<` becomes `>`) my bad fixed in answer – ratchet freak Oct 06 '11 at 22:18
4

One line of code:

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

It's easy to maintain by JDK library.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
1

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

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;
    }
}
lukastymo
  • 26,145
  • 14
  • 53
  • 66
0

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;
    }
}
Jake
  • 600
  • 8
  • 20