Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for pairwise iteration through a sorted collection

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 Lists (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.

like image 946
Raedwald Avatar asked Jul 03 '13 16:07

Raedwald


1 Answers

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;
    }
}
like image 178
Brigham Avatar answered Oct 14 '22 09:10

Brigham