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 collection and the next element of the collection?
For sorted List
s (and arrays), it can be done using an index into the collection:
final int n = list.size();
assert 2 <= n;
for (int i = 0; i < n - 1; ++i) {
final Thing thing1 = list.get(i);
final Thing thing2 = list.get(i+1);
operateOnAdjacentPair(thing1, thing2);
}
But what about SortedSet
? (for SortedMap
you can use its entrySet()
, which is equivalent to the SortedSet
case).
So, for example, if your sorted set contained the values {1, 2, 3, 4}, the iterations would be for the pairs (1, 2), (2, 3), (3, 4), in that order.
Iterator<Thing> thingerator = coll.iterator();
if (thingerator.hasNext()) {
Thing thing1 = thingerator.next();
while (thingerator.hasNext()) {
final Thing thing2 = thingerator.next();
doStuffToThings(thing1, thing2);
thing1 = thing2;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With