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

We know that we cannot directly access elements of a stream in Java 8 and above by using their indices, unlike in lists and arrays, but there are few workarounds in Java that makes this feasible. These are discussed below in detail:

1. Using IntStream

We can take advantage of the fact that elements in an array or a collection are accessible using an index. The idea is to get an IntStream of array indices, ranging from 0 to n-1, where n is the array’s length. Then we use the mapToObj(mapper) method to returns a stream of string, as shown below:

Download  Run Code

Output:

0 -> A
1 -> B
2 -> C
3 -> D

 
We can also write the above code as:

2. Using AtomicInteger

We can also use AtomicInteger class in Java. The idea is to get a sequential stream of an array or the collection and call getAndIncrement() to get the next index, as shown below:

Download  Run Code

Output:

0 -> A
1 -> B
2 -> C
3 -> D

 
We can also write the above code as:

 
Please note that this approach won’t work with parallel streams as the processing order of the elements in the stream might differ from the original order of the array elements.

3. Using Guava’s Streams Class

We know that the Guava Streams class provides several static utility methods related to stream instances. One such method is mapWithIndex, which returns a stream consisting of the results of applying the specified method to the elements of the stream and their indices in the stream.

Download Code

Output:

0 -> A
1 -> B
2 -> C
3 -> D

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