Skip to content
Advertisement

How to get next key/value pair of linkedhashmap using enhanced for loop in Java

How do we get next key/value pair of a linkedhashmap using an enhanced for loop in Java?

What we want to achieve is to get a value from a linkedhashmap and pair it with the next value in the linkedhashmap. To achieve this, first of all, we have a list looking like the following:

JavaScript

Above outputs:

JavaScript

Then we want to select 2021-01-01 and then pair it with 2021-03-31. We then want 2021-04-01 and pair it with its next value, which is 2021-06-30 and so on… To achieve this, we have a function, where we initialize a enhanced for loop to get the values of the linkedhashmap. We use modulo to only select every second date starting from the first date, but we are only able to retrieve the first value, but not the second. Then using modulo, we select the third, but not the fourth value.

JavaScript

Above should output the following:

JavaScript

How can it be programmed correctly in Java?

Advertisement

Answer

You can’t do this with an enhanced for loop. You have to use an Iterator directly:

JavaScript

If dates isn’t large, it may be easier to copy into a List, and then access by index:

JavaScript

Really, a (LinkedHash)Map isn’t an ideal structure to be holding together pairs of keys with semantic meaning. It would be better to store those keys together, as a single key object.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement