Is there a Java idiom for pairwise iteration through the elements of a sorted Collection
? By that I mean that each iteration has access to one element of the co
For Set
s (and other non-indexable collections) you will need to use their Iterators as returned by the iterator() method of Collection
:
Iterator iter = set.iterator();
Thing thing1 = iter.next(); // might want to check if this exists
while (iter.hasNext()) {
Thing thing2 = iter.next();
operateOnAdjacentPair(thing1, thing2);
thing1 = thing2;
}
You can do the same for Map
s, using the Iterator
of their entrySet()s.
Now that I understand your question better, you could also try this:
Iterator iter1 = set.iterator(), iter2 = set.iterator();
if (iter2.hasNext())
iter2.next(); // burn first element
while (iter2.hasNext()) {
final Thing thing1 = iter1.next();
final Thing thing2 = iter2.next();
operateOnAdjacentPair(thing1, thing2);
}