To iterate over a Stream with Indices in Java 8, the code is as follows −
Example
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.