Java, How do I get current index/key in "for each" loop
JavaJava Problem Overview
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";
}
Java Solutions
Solution 1 - Java
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 - Java
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 - Java
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 - Java
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 - Java
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.
Solution 6 - Java
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.