Array indexing
If you have an array-like data-structure (e.g. an actual array or something like an ArrayList
), then referencing i
, i-1
, i+1
will give good performance so there isn't much more to it. (Although having to turn a For-Each Loop into an index counting For Loop isn't very fun and is one of the few caveats.)
The answer offered by Sergey does something like this.
The versatile ListIterator
If you can get your hands on an ListIterator
(which is actually quite a big assumption), the answer offered by Suraj could suffice. But do note both next()
and previous()
moves the iterator position. So if you did something like the following for each loop iteration: prev = previous(); current = next(); next = next(); previous()
, you'll end up performing roughly 4 iteration operations per loop. This isn't much of a problem if iteration is cheap, and luckily this is often the case for data-structures that offers a ListIterator
.
Generic solution
The generic solution for any Iterable
(or Iterator
) should make no random lookups (as is possible with an array) or make assumptions regarding performance of next()
, which should be called at most N times where N is the number of available elements.
Here's one such 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
}
Mind, this implementation has caveats of its own:
- It'll break if
Iterable
contains null
elements.
- Neither
current
or next
are effectively-final, so cannot be used directly in them fangled Java 8 lambdas.