Use TreeMap
, it keeps keys sorted (in increasing order, by default).
To iterate through entries, you can use one of these approaches:
Lambda for-each:
weatherMap.forEach((date, temp) -> {
// your code
});
Traditional for-each:
for (Map.Entry<LocalDate, Integer> entry : weatherMap.entrySet()) {
// your code
}
If you want to keep track of value changes between iterations, the latter is more convenient:
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…