How to get the current loop index when using Iterator?

Mahmoud Saleh picture Mahmoud Saleh · Jul 25, 2010 · Viewed 166.5k times · Source

I am using an Iterator to iterate through a collection and I want to get the current element's index.

How can I do that?

Answer

Paul picture Paul · Dec 16, 2011

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 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().