Program to Iterate over a Stream with Indices in Java 8
In Java 8, we can iterate over a stream with indices using the IntStream
class. Here's an example program that demonstrates how to do this:
import java.util.stream.IntStream;
public class StreamWithIndicesExample {
public static void main(String[] args) {
String[] words = {"hello", "world", "java", "stream"};
IntStream.range(0, words.length)
.forEach(i -> System.out.println(i + ": " + words[i]));
}
}
In this program, we have an array of strings words
. We use the IntStream.range
method to create a stream of integers from 0 to the length of the array. We then use the forEach
method to iterate over the stream and print out each index and its corresponding element in the array.
Output:
0: hello
1: world
2: java
3: stream
Another way to achieve the same result is by using the Stream.iterate
method. Here's an example program that demonstrates how to do this:
import java.util.stream.Stream;
public class StreamWithIndicesExample {
public static void main(String[] args) {
String[] words = {"hello", "world", "java", "stream"};
Stream.iterate(0, i -> i + 1)
.limit(words.length)
.forEach(i -> System.out.println(i + ": " + words[i]));
}
}
In this program, we use the Stream.iterate
method to create a stream of integers starting from 0 and incrementing by 1. We then use the limit
method to limit the stream to the length of the array. Finally, we use the forEach
method to iterate over the stream and print out each index and its corresponding element in the array.
Output:
0: hello
1: world
2: java
3: stream