How to get the current loop index when using Iterator?
Solution 1:
I had the same question and found using a ListIterator
worked. Similar to the test above:
List<String> list = Arrays.asList("zero", "one", "two");
ListIterator<String> iter = list.listIterator();
while (iter.hasNext()) {
System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}
Make sure you call the nextIndex()
before you actually get the next()
.
Solution 2:
Use your own variable and increment it in the loop.
Solution 3:
Here's a way to do it using your own variable and keeping it concise:
List<String> list = Arrays.asList("zero", "one", "two");
int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
String s = it.next();
System.out.println(i + ": " + s);
}
Output (you guessed it):
0: zero
1: one
2: two
The advantage is that you don't increment your index within the loop (although you need to be careful to only call Iterator#next once per loop - just do it at the top).