1

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?

2
  • 2
    If you're using HashMap, you need to bear in mind that it doesn't preserve insert-order. If you need the insert-order then you need to use LinkedHashMap. Commented Sep 17, 2009 at 1:20
  • @Tom: sorted maps don't preserve input order per se - they preserve sort order, which is often a different thing, no? Commented Sep 17, 2009 at 12:30

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

I wonder if that is forcing a use of the posh for loop, and that we should drop to using iterators instead.
when would one use an iterator instead of a loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.