Program to Iterate over a Stream with Indices in Java 8

JavaObject Oriented ProgrammingProgramming

To iterate over a Stream with Indices in Java 8, the code is as follows −

Example

 Live Demo

import java.util.stream.IntStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Demo{
   public static void main(String[] args){
      String[] my_array = { "T", "h", "i", "s", "s","a", "m", "p", "l", "e" };
      AtomicInteger my_index = new AtomicInteger();
      System.out.println("The elements in the string array are :");
      Arrays.stream(my_array).map(str -> my_index.getAndIncrement() + " -> " + str).forEach(System.out::println);
   }
}

Output

The elements in the string array are :
0 -> T
1 -> h
2 -> i
3 -> s
4 -> s
5 -> a
6 -> m
7 -> p
8 -> l
9 -> e

A class named Demo contains the main function. In this main function, an array of string type is declared and the AtomicInteger instance is created using the AtomicInteger class. The ‘getAndIncrement’ function is used to iterate over the elements of the string array and every element iterated over is printed on to the console.

raja
Published on 07-Jul-2020 13:21:14
Advertisements