I have a code which is as follows:
Arrays.stream(myArray).forEach(item -> System.out.println(item));
Does streams in Java have any ability of getting the index of the current item that I can use them inside the lambda expression?
For example in JavaScript we have this kind of code which can give us the index:
myArray.forEach((index, item) => console.log(`${index} ${item}`));
Do we have any equivalent in Java?
Yes to answer your question, in Java you can iterate over a stream with indices.
This is a very simple basic code which shows how to get the index :
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
String[] array = { "Goat", "Cat", "Dog", "Crow", "Snake" };
IntStream.range(0, array.length)
.mapToObj(index -> String.format("%d -> %s", index, array[index]))
.forEach(System.out::println);
}
}
Output :
0 -> Goat
1 -> Cat
2 -> Dog
3 -> Crow
4 -> Snake
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With