Java stream forEach with index

In this tutorial, we will learn about how to iterate over a Java stream with the index. We can do this in different ways, using Intstream, AtomicInteger. etc. Here we will learn iterating over a Java stream with index using IntStream.

We all know about how to iterate or traverse a Java stream using loops i.e.for-loop, do-while loop, and while loop.

In the case of traversing the array or collection of elements we mostly use for loop.

for(int i=0;i<n;i++)
{
System.out.println(array[i]);
}

Similarly, there are other ways too through which we can traverse or iterate through the stream. These loops are the external part of the collection of elements and therefore, they are much slower than the forEach() loop. The forEach() loop is the internal part of the collection i.e. internal loops that help in traversing through the array or collection elements. In the case of a huge collection of elements, it is most appropriate to use a forEach loop.

forEach loop

In forEach loop, with the help of a variable, we will iterate over the Java streams and do the respective tasks using this loop. Like below we are just printing the data present in the array list named arr.

arr.forEach(i -> System.out.println(i));

The forEach loop makes the code easy to read and reduces the code’s errors. The only disadvantage with forEach is that we cannot traverse the stream or the list in reverse order and also we cannot skip any element present in the list. It iterates over every element present in the list or collection of elements.

forEach loop with index

Firstly, we will include two packages :

import java.util.stream.IntStream;

This package includes all the methods present in IntStream like range() method, mapToObj() method, etc.

Now here we not only have to traverse through the list or the stream but we also have to print the elements with their index. Therefore, here we will use IntStream using the range() method. IntStream is used to traverse or iterate through the elements of the collection or stream and manipulate int values. This method generates a collection of numbers starting and ending (stops before reaching the end) according to the parameter. After that, we will map the elements present in the array list or the collection of elements with the index using the mapToObj(mapper) method. The mapToObj(mapper) method also belongs to IntStream. This method is basically used to return an object-valued stream.

Using these methods with forEach loop, we will be able to print the elements present in the stream with their associated index.

This way:

IntStream.range(0, arr.length).mapToObj(index -> String.format("%d -> %s", 
                      index, arr[index]))
            .forEach(System.out::println);

Here arr is the name of the array list and the range() method ranges between 0 and the length of the array. mapToObj(mapper) method in IntStream maps the elements with the associative indices whereas forEach loop print the stream with the respective index.

The complete code:

import java.util.*;
import java.util.stream.IntStream;


public class Main
{
  
    public static void main(String[] args)
    {
         Scanner input = new Scanner(System.in);
         int n;
         System.out.println("Enter the number of elements to be inserted");
         n = input.nextInt();
         int[] arr = new int[n];  
               System.out.println("Enter the elements of the array: ");  
          for(int i=0; i<n; i++)  
          {  
               arr[i]=input.nextInt();  
          }
        IntStream
            .range(0, arr.length)
            .mapToObj(index -> String.format("%d -> %s", 
                                       index, arr[index]))
            .forEach(System.out::println);
    }
}

On executing the above code:

Output:

Enter the number of elements to be inserted

3

Enter the elements of the array:

22

33

44

The elements with their indices are:

0 -> 22

1 -> 33

2 -> 44

Hope this tutorial was useful.

Leave a Reply

Your email address will not be published.