如何在 HashMap 中找到最小值

How to find the lowest value in a HashMap

我想输出HashMap中的最小值。到目前为止,我可以遍历 HashMap 并打印出它的值,但我不确定如何比较地图本身的值并打印出最小值的键和值。这就是我迭代的方式:

for (HashMap.Entry<String, Integer> entry : itemTime.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}

在你的循环中,将值与当前最小值进行比较并记住最小值:

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);

我想你想要的是对你的 hashmap 进行排序。 Java 有您可以为此使用的库。

您也可以只将第一个键-->值设置为您的 'smallest',然后遍历哈希图的其余部分检查 if(currentValue < smallestValue)

据我了解,java 散列图会自动按键排序。 IE,如果你有键--> weight, height, age...你的hashmap中的第一个键是'age',最后一个是'weight'

我认为最简单的方法是使用 Stream:

public static Map.Entry<Integer, Integer> getSmallestValue(Map<Integer, Integer> map) {
    return map.entrySet().stream().min(Comparator.comparingInt(Map.Entry::getValue)).orElse(null);
}