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

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";
}

This question is related to java

The answer is


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"


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.


Example from current code I'm working with:

int index=-1;
for (Policy rule : rules)
{   
     index++;
     // do stuff here
}

Lets you cleanly start with an index of zero, and increment as you process.


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

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

Not possible in Java.


Here's the Scala way:

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

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

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.


###################################################
###################################################
###################################################
AVOID THIS
###################################################
###################################################
###################################################

/*for (Song s: songList){
    System.out.println(s + "," + songList.indexOf(s); 
}*/

it is possible in linked list.

you have to make toString() in song class. if you don't it will print out reference of the song.

probably irrelevant for you by now. ^_^