Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - How to compare single hashmap values

I'm trying to use the HashMap to check the weather in a certain period For example one week. I need to check if the weather becoming colder, warmer, same, or unsteady.

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

can anyone help me with iterating inside the values and check them

question from:https://stackoverflow.com/questions/65845382/how-to-compare-single-hashmap-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...