Iterate over a Stream with Indices in Java 8

In this post, we will discuss how to iterate over a Stream with indices in Java 8.


 

We know that elements of Streams in Java 8 cannot be directly accessed by using their indices unlike in lists and arrays, but there are few workarounds in Java that makes this feasible which 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 length of the array. Then we use mapToObj(mapper) function 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 above code as:

 

2. Using AtomicInteger

We can also use AtomicInteger class in Java. The idea is to get an 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 above code as:

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

 

3. Using Guava Streams Class –

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

 

Download   Run Code

Output:

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz