Array indexing
If you have a data structure similar to an array (for example, an actual array or something like ArrayList ), then a link i , i-1 , i+1 will give good performance, so there is not much more. (Despite the fact that for every For-Each Loop loop, the For Loop index counter is not very funny and is one of the few caveats.)
The answer suggested by Sergey does something like this.
Generic ListIterator
If you can get a ListIterator (which is actually a pretty big guess), the answer suggested by Suraj might be enough. But note that next() and previous() move the position of the iterator . Therefore, if you did something like the following for each iteration of the loop: prev = previous(); current = next(); next = next(); previous() prev = previous(); current = next(); next = next(); previous() prev = previous(); current = next(); next = next(); previous() , you will complete approximately 4 iteration operations for each loop. This is not a big problem if the iteration is cheap , and, fortunately, this is often the case for data structures that offer a ListIterator .
Common decision
The general solution for any Iterable (or Iterator ) should not do random searches (as is possible with an array) or make assumptions regarding next() performance, which should be called no more than N times, where N is the number of available elements.
Here is one of these implementations:
final Iterator<E> it = iterable.iterator(); for (E next = (it.hasNext() ? it.next() : null), current = null; next != null;) { E previous = current; current = next; next = it.hasNext() ? it.next() : null; // Do something using 'current', 'previous' and 'next'. // NB: 'previous' and/or 'next' are null when 'current' is // the first and/or last element respectively }
Reason, this implementation has its reservations:
- It will break if
Iterable contains null elements. - Neither the
current nor the next are valid, so they cannot be used directly in them fangled Java 8 lambdas.
source share