This post will discuss how to iterate over a list with indices in Java.

1. Using ListIterator

The standard solution to iterate over a list with indices is using the ListIterator, which contains the previousIndex() and nextIndex() method returning the index of the previous and next element in the list respectively.

The following code demonstrates the working of nextIndex() to get the index of each element. Note that the solution calls the nextIndex() method before calling the next() method. Alternatively, you can call the previousIndex() method after calling the next() method.

Download  Run Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

2. For loop

A simple approach is to use a regular for-loop to iterate over the list elements, and use the loop counter as the index and get its corresponding element using the get() method.

Download  Run Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

3. Using IntStream

With Java 8, you can get an IntStream of the list indices, and use it to get the corresponding list element with the get() method. Here’s a Java 8 one-liner demonstrating this approach:

Download  Run Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

4. Using Guava

Java 8 streams API lacks the ability to get the index of a stream element. Since Guava 21, you can use the Streams.mapWithIndex() method to get the indexes of elements in the stream. For example,

Download Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

5. Using enhanced for loop

If you prefer enhanced for loop over regular for loop, you can maintain a counter to keep track of the current index, as shown below:

Download  Run Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

6. Using AtomicInteger

If you prefer Java 8 forEach() over the traditional and enhanced for-loop, you can keep track of the index in a mutable object, like AtomicInteger, and use it as demonstrated below.

Note that the variables used within the lambda expression must be final or effectively final. Therefore, one cannot maintain the current index in a primitive counter.

Download  Run Code

Output:

Item a is located at index 0
Item b is located at index 1
Item c is located at index 2
Item d is located at index 3

That’s all about iterating over a List with indices in Java.