This post will discuss how to find the current index in a for-each loop in Java.

The for-each loop simplifies the code by hiding the complexity behind the iterator() method. There is no direct provision to access the index of the current element with for-each construct, since it is used to loop over an Iterable, and not all Iterables actually have an index. This post provides an overview of some of the available alternatives to accomplish this.

1. Maintain a counter

A simple solution is to maintain an explicit counter, starting with 0, and increment the counter by 1 in each iteration of the loop. Here’s how the code would look like:

Download  Run Code

Output:

Index: 0, Element: 4
Index: 1, Element: 2
Index: 2, Element: 5
Index: 3, Element: 4
Index: 4, Element: 1

 
If there is no special reason to use the for-each loop, you should use a regular for loop to easily get the index for each element.

Download  Run Code

Output:

Index: 0, Element: 4
Index: 1, Element: 2
Index: 2, Element: 5
Index: 3, Element: 4
Index: 4, Element: 1

2. Using AtomicInteger

We know that the variables used inside a lambda expression must be final or effectively final, hence a primitive integer variable cannot be used with a lambda expression. If you prefer Java 8 forEach() over the classical and enhanced for-loop, you can keep track of the index in an AtomicInteger.

Download  Run Code

Output:

Index: 0, Element: 4
Index: 1, Element: 2
Index: 2, Element: 5
Index: 3, Element: 4
Index: 4, Element: 1

 
Alternatively, you can just iterate over the indices of the elements using an IntStream, as shown below:

Download  Run Code

Output:

Index: 0, Element: 4
Index: 1, Element: 2
Index: 2, Element: 5
Index: 3, Element: 4
Index: 4, Element: 1

3. Using ListIterator

Finally, you can use the iterator returned by the listIterator() method, which has the nextIndex() method. It returns the index of the element that would be returned by a subsequent call to the next() method.

Download  Run Code

Output:

Index: 0, Element: 4
Index: 1, Element: 2
Index: 2, Element: 5
Index: 3, Element: 4
Index: 4, Element: 1

That’s all about finding the current index in a for-each loop in Java.