views:

252

answers:

2

I have this loop:

 for (Map.Entry<Integer, String> entry: collection.entrySet()) {

 }

I'd like to compare entry and the next one after that. How would I do it?

+4  A: 

As you loop over you could set a variable called oldEntry for example (initialized to null) and use that in the way you want.

 Map.Entry<Integer,String> oldEntry = null;
 for (Map.Entry<Integer, String> entry: collection.entrySet()) {
   if (oldEntry != null) doStuff(oldEntry, newEntry);
   oldEntry = entry;
 }
joeslice
I wonder if that is forcing a use of the posh for loop, and that we should drop to using iterators instead.
Tom Hawtin - tackline
when would one use an iterator instead of a loop?
Rosarch
+5  A: 

You do it on the previous one.

Map.Entry<Integer, String> previous = null;
for (Map.Entry<Integer, String> entry : collection.entrySet()) {
  if (previous != null) {
    // compare entry to rpevious
  }
  previous = entry;
}
cletus