0

I want to output the lowest value from a HashMap. So far, I can iterate through the HashMap and print out it's values, but I'm not sure how to compare the values in the map itself and print out the key and value for the smallest one. This is how I am iterating:

for (HashMap.Entry<String, Integer> entry : itemTime.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
sopatd
  • 27
  • 1
  • 2
  • 6

3 Answers3

3

In your loop, compare the value to the current smallest and remember the smallest:

Integer smallestValue = Integer.MAX_VALUE;
String smallestKey;
for (HashMap.Entry<String, Integer> entry : itemTime.entrySet()) {
    if (entry.getValue() < smallestValue) {
        smallestKey = entry.getKey();
        smallestValue = entry.getValue();
    }
    System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.pintln("Smallest is " + smallestKey + " with " + smallestValue);
Robert
  • 7,394
  • 40
  • 45
  • 64
1

I think the easiest way is to use Stream:

public static Map.Entry<Integer, Integer> getSmallestValue(Map<Integer, Integer> map) {
    return map.entrySet().stream().min(Comparator.comparingInt(Map.Entry::getValue)).orElse(null);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
-1

I think what you want is to sort your hashmap. Java has libraries you can utilize for this.

You could also just set the first key-->value as your 'smallest' and then iterate through the rest of the hashmap checking if(currentValue < smallestValue)

It is my understanding that java hashmaps are automatically sorted by key. IE if you had keys --> weight, height, age... the first key in your hashmap would be 'age', last would be 'weight'

mumbu22
  • 56
  • 2
  • Hashmaps are not sorted by default. The key may not even provide a reasonable ordering (see the Comparable interface). You can use a LinkedHashMap to preserve insertion order (time), but that's not a key thing. – Robert Aug 16 '20 at 20:49