英文:
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());
}
英文:
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());
}
答案1
得分: 3
在你的循环中,将该值与当前最小值进行比较,并记住最小值:
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("最小值为 " + smallestKey + ",对应值为 " + smallestValue);
英文:
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);
答案2
得分: 1
我认为最简单的方法是使用 Stream
:
public static Map.Entry<Integer, Integer> getSmallestValue(Map<Integer, Integer> map) {
return map.entrySet().stream().min(Comparator.comparingInt(Map.Entry::getValue)).orElse(null);
}
英文:
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);
}
答案3
得分: -1
我认为你想要的是对你的哈希映射进行排序。Java有可以利用的库。
你也可以将第一个键-->值设置为你的“最小值”,然后迭代遍历哈希映射的其余部分,检查是否(currentValue < smallestValue)
据我了解,Java哈希映射会自动按键排序。也就是说,如果你有键-->重量,身高,年龄...那么哈希映射中的第一个键将是“年龄”,最后一个将是“重量”。
英文:
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论