2

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
M.barg
  • 31
  • 1
  • 1
  • 3
  • 1
    Does this answer your question? [Get Index while iterating list with stream](https://stackoverflow.com/questions/49080255/get-index-while-iterating-list-with-stream) – Bashir Jun 26 '20 at 16:43
  • 1
    You can check this https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8 – Harmandeep Singh Kalsi Jun 26 '20 at 16:44
  • 2
    Does this answer your question? [Is there a concise way to iterate over a stream with indices in Java 8?](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8) – mohammedkhan Jun 26 '20 at 16:46

1 Answers1

1

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
Som
  • 1,522
  • 1
  • 15
  • 48