271

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";
}
droidgren
  • 6,338
  • 8
  • 29
  • 27

7 Answers7

391

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"

Michael Mrozek
  • 149,906
  • 24
  • 156
  • 163
  • 4
    This is indeed the correct answer semantically, for each loop can iterate through streaming data from a remote database which is being updated while you're iterating through its contents (if the used iterator actually does that) in which case there's no way of knowing the current index. Index is just a *view* to the data, not a property of data. – Esko Aug 07 '10 at 18:26
  • 1
    Although it might be no index, it would be very convenient to have some kind of iteration counter that you can access inside the loop. I guess such thing can hardly end in core java, more chances for some of the scripting languages. – akostadinov Apr 01 '13 at 11:11
  • As I was afraid, maybe in Java 12 they will add it as a feature to be proud of, as they recently did with lambdas and reading files with one-liners? (DISCLAIMER: I am (mostly) a Java programmer myself) – Andreas Tasoulas Dec 18 '14 at 12:37
  • 1
    @atas 2.5 years closer to Java 12... The index is definitely available, i.e. it's on the stack, if you're dealing with an array. It would be really cool if there was a keyword that would compile to a simple "ILOAD 2". If it's a List, it compiles to an iterator, which won't be able to give you an index. – Bjørn Vårdal Aug 02 '17 at 00:25
16

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.

TheLQ
  • 14,081
  • 11
  • 66
  • 104
12

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

 int index = 0;
    for (Element song: question){
        // Do whatever
         index++;
    }
Saher Ahwal
  • 8,230
  • 28
  • 75
  • 136
  • 3
    That's true, but as much as I love the enhanced for-each loop introduced in Java5, doesn't supplying your own index defeat the purpose of simply using the traditional for-each construct? Using what's built into Java will often be more intuitive / readable (though not always) to the Java developer. – Michael M Jun 11 '17 at 19:39
  • 6
    7 years later... ( wow I can't believe it, time flies) , I agree with you @MichaelM 100%. – Saher Ahwal Jun 12 '17 at 18:16
10
###################################################
###################################################
###################################################
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. ^_^

Ele
  • 31,191
  • 6
  • 31
  • 67
EdenB
  • 585
  • 4
  • 3
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)
Zeffer
  • 89
  • 1
2

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.

likejudo
  • 2,611
  • 6
  • 39
  • 83
-5

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.

  • 4
    Simply cumbersome. Start at zero and implement at the end. Unless you use continue in the body of the loop. – gabor Jun 12 '17 at 11:32