Java, How do I get current index/key in "for each" loop
To get the current index/key in a "for each" loop, you can use the for
loop instead. Here's an example:
List<String> list = Arrays.asList("a", "b", "c");
for (int i = 0; i < list.size(); i++) {
String item = list.get(i);
// Use i as the index/key here
}
Alternatively, you can use the ListIterator
class to iterate through the list and get the current index/key:
List<String> list = Arrays.asList("a", "b", "c");
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
String item = iterator.next();
int index = iterator.previousIndex();
// Use index as the key here
}
Note that the for each
loop is simply a shorthand for iterating through a collection and is not meant to provide access to the current index/key. If you need to access the index/key, you'll need to use one of the approaches mentioned above.