[英]How to compare single hashmap values
我正在尝试使用 HashMap 来检查某个时期的天气,例如一周。 我需要检查天气是否变冷、变暖、相同或不稳定。
Map<LocalDate , Integer > weatherMap = new HashMap<>();
weatherMap.put(LocalDate.of(2020,12,12), 12);
weatherMap.put(LocalDate.of(2020,12,13), 11);
weatherMap.put(LocalDate.of(2020,12,14), 10);
谁能帮我在值内部迭代并检查它们
使用TreeMap
,它使键保持排序(默认情况下按升序排列)。 要遍历条目,您可以使用以下方法之一:
Lambda 对于每个:
weatherMap.forEach((date, temp) -> {
// your code
});
传统的for-each:
for (Map.Entry<LocalDate, Integer> entry : weatherMap.entrySet()) {
// your code
}
如果要跟踪迭代之间的值变化,后者更方便:
int prevTemp = -100;
for (Map.Entry<LocalDate, Integer> entry : weatherMap.entrySet()) {
int curTemp = entry.getvalue();
if (prevTemp != -100) { // there was a previous temp
// your code - compare with curTemp
}
prevTemp = curTemp;
}
您可以增加日期并检查 HashMap 以了解特定日期的温度:
LocalDate startDate = LocalDate.of(2020,12,12);
int numberOfDays=7;
int temp = 12;
for(int i=0;i<numberOfDays;i++){
int newTemp = weatherMap.getOrDefault(startDate, temp);
/* your code to compare temperatures*/
temp=newTemp;
}
您也可以使用迭代器...经典方法如下所示:
Set s = map.entrySet();
Iterator i = s.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
使用迭代器的最短方法是这个。 我没有测试我无法说出其中逻辑的代码,但它应该看起来像这样。 也许您将不得不使用 AtomicInteger 而不是 int:
int temp = 0;
int loop = 0;
weatherMap.entrySet()
.forEach((entry) -> {
System.out.println(entry.getKey() + " : " + entry.getValue())
if(loop == 0) {
temp = entry.getValue()
}
if(loop != 0 && temp > entry.getValue()) {
// it's hotter
temp = entry.getValue()
} else if(temp < entry.getValue()) {
// colder
temp = entry.getValue()
} else {
// Same temp
}
loop++;
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.