如何解决如何在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);
,
我认为最简单的方法是使用Stream
:
public static Map.Entry<Integer,Integer> getSmallestValue(Map<Integer,Integer> map) {
return map.entrySet().stream().min(Comparator.comparingInt(Map.Entry::getValue)).orElse(null);
}
,
我认为您想要的是对哈希图进行排序。 Java有可用于此目的的库。
您还可以只将第一个键-> value设置为“最小”,然后遍历哈希表的其余部分,检查if(currentValue 据我了解,Java哈希图是按键自动排序的。 IE,如果您有键->体重,身高,年龄...哈希表中的第一个键是“年龄”,最后一个是“体重”
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。