Given a Stream in Java, the task is to iterate over it with the help of indices.
Examples:
Input: Stream = [G, e, e, k, s]
Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s]Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s]
Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s]
- Method 1: Using IntStream.
- Get the Stream from the array using range() method.
- Map each elements of the stream with an index associated with it using mapToObj() method
- Print the elements with indices
// Java program to iterate over Stream with Indices
Â
Âimport
java.util.stream.IntStream;
Â
Âclass
GFG {
   Â
public
static
void
main(String[] args)
   Â
{
Â
ÂÂ Â Â Â Â Â Â Â
String[] array = {
"G"
,
"e"
,
"e"
,
"k"
,
"s"
};
Â
ÂÂ Â Â Â Â Â Â Â
// Iterate over the Stream with indices
       Â
IntStream
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Get the Stream from the array
           Â
.range(
0
, array.length)
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Map each elements of the stream
           Â
// with an index associated with it
           Â
.mapToObj(index -> String.format(
"%d -> %s"
,Â
                                      Â
index, array[index]))
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Print the elements with indices
           Â
.forEach(System.out::println);
   Â
}
}
Output:0 -> G 1 -> e 2 -> e 3 -> k 4 -> s
- Method 2: Using AtomicInteger.
- Create an AtomicInteger for index.
- Get the Stream from the array using Arrays.stream() method.
- Map each elements of the stream with an index associated with it using map() method where the index is fetched from the AtomicInteger by auto-incrementing index everytime with the help of getAndIncrement() method.
- Print the elements with indices.
// Java program to iterate over Stream with Indices
Â
Âimport
java.util.stream.IntStream;
import
java.util.*;
import
java.util.concurrent.atomic.AtomicInteger;
Â
Âclass
GFG {
   Â
public
static
void
main(String[] args)
   Â
{
Â
ÂÂ Â Â Â Â Â Â Â
String[] array = {
"G"
,
"e"
,
"e"
,
"k"
,
"s"
};
Â
ÂÂ Â Â Â Â Â Â Â
// Create an AtomicInteger for index
       Â
AtomicInteger index =
new
AtomicInteger();
Â
ÂÂ Â Â Â Â Â Â Â
// Iterate over the Stream with indices
       Â
Arrays
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Get the Stream from the array
           Â
.stream(array)
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Map each elements of the stream
           Â
// with an index associated with it
           Â
.map(str -> index.getAndIncrement() +
" -> "
+ str)
Â
ÂÂ Â Â Â Â Â Â Â Â Â Â Â
// Print the elements with indices
           Â
.forEach(System.out::println);
   Â
}
}
Output:0 -> G 1 -> e 2 -> e 3 -> k 4 -> s