I want to go through a map with integer keys that are in the range of 14000-18000. I want to go through them and print the relative difference between them. So if there were three keys 14152 and 14153, 14159, the print output would be 0, 1, 7.
I have put my keys and values into a TreeMap, since it stores things in order.
However, with my implementation:
int dayCounter = 0;
for (Entry<Integer, String> entry : map.entrySet())
{
builder.append(dayCounter);
dayCounter = entry.getKey();
}
I am going through the map but know no way of getting the “previous” entry. If I was using an array I could get the (i-1)th value and subtract from i to get the relative value. Is there any way to get thie functionality with java maps?
When you iterate, you know you have the smallest value first. So I would do something like this:
Using your example:
Results in
Now, it’s possible that’s not what you intended. Perhaps you want the difference between each node, which not what your example shows. In that case, I would leverage the Collections library like this:
Here’s an example of that, incase it’s what oyu actually intended:
Results in