Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the index of item inside the Java streams? [duplicate]

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?

like image 234
M.barg Avatar asked Oct 26 '25 00:10

M.barg


1 Answers

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
like image 90
Som Avatar answered Oct 27 '25 17:10

Som