'Java, How do I get current index/key in "for each" loop [duplicate]

In Java, How do I get the current index for the element in Java?

for (Element song: question){
    song.currentIndex();         //<<want the current index.
}

In PHP you could do this:

foreach ($arr as $index => $value) {
    echo "Key: $index; Value: $value";
}


Solution 1:[1]

You can't, you either need to keep the index separately:

int index = 0;
for(Element song : question) {
    System.out.println("Current index is: " + (index++));
}

or use a normal for loop:

for(int i = 0; i < question.length; i++) {
    System.out.println("Current index is: " + i);
}

The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"

Solution 2:[2]

In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.

Solution 3:[3]

Keep track of your index: That's how it is done in Java:

 int index = 0;
    for (Element song: question){
        // Do whatever
         index++;
    }

Solution 4:[4]

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

Solution 5:[5]

As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Mrozek
Solution 2 TheLQ
Solution 3
Solution 4 Maifee Ul Asad
Solution 5 likejudo