How to get the current loop index when using Iterator?

JavaIterator

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

Use your own variable and increment it in the loop.

Solution 3 - Java

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

Solution 4 - Java

You can use ListIterator to do the counting:

final List<String> list = Arrays.asList("zero", "one", "two", "three");

for (final ListIterator<String> it = list.listIterator(); it.hasNext();) {
    final String s = it.next();
    System.out.println(it.previousIndex() + ": " + s);
}

Solution 5 - Java

What kind of collection? If it's an implementation of the List interface then you could just use it.nextIndex() - 1.

Solution 6 - Java

Use an int and increment it within your loop.

Solution 7 - Java

Use a ListIterator to iterate through the Collection. If the Collection is not a List to start with use Arrays.asList(Collection.toArray()) to turn it into a List first.

Solution 8 - Java

just do something like this:

        ListIterator<String> it = list1.listIterator();
        int index = -1;
        while (it.hasNext()) {
            index++;
            String value = it.next();
            //At this point the index can be checked for the current element.

        }

Solution 9 - Java

See here.

iterator.nextIndex() would provide index of element that would be returned by subsequent call to next().

Solution 10 - Java

All you need to use it the iterator.nextIndex() to return the current index that the iterator is on. This could be a bit easier than using your own counter variable (which still works also).

public static void main(String[] args) {	
	String[] str1 = {"list item 1", "list item 2", "list item 3", "list item 4"};
	List<String> list1 = new ArrayList<String>(Arrays.asList(str1));
	
	ListIterator<String> it = list1.listIterator();
	
	int x = 0;
	
	//The iterator.nextIndex() will return the index for you.
	while(it.hasNext()){
        int i = it.nextIndex();
		System.out.println(it.next() + " is at index" + i);	
	}
}

This code will go through the list1 list one item at a time and print the item's text, then "is at index" then it will print the index that the iterator found it at. :)

Solution 11 - Java

Though you already had the answer, thought to add some info.

As you mentioned Collections explicitly, you can't use listIterator to get the index for all types of collections.

List interfaces - ArrayList, LinkedList, Vector and Stack.

Has both iterator() and listIterator()

Set interfaces - HashSet, LinkedHashSet, TreeSet and EnumSet.

Has only iterator()

Map interfaces - HashMap, LinkedHashMap, TreeMap and IdentityHashMap

Has no iterators, but can be iterated using through the keySet() / values() or entrySet() as keySet() and entrySet() returns Set and values() returns Collection.

So its better to use iterators() with continuous increment of a value to get the current index for any collection type.

Solution 12 - Java

This would be the simplest solution!

std::vector<double> v (5);

for(auto itr = v.begin();itr != v.end();++itr){

 auto current_loop_index = itr - v.begin();

  std::cout << current_loop_index << std::endl;

}

Tested on gcc-9 with -std=c++11 flag

Output:

> 0
1
2
3
4

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMahmoud SalehView Question on Stackoverflow
Solution 1 - JavaPaulView Answer on Stackoverflow
Solution 2 - JavaChris DiverView Answer on Stackoverflow
Solution 3 - JavaTom CliftView Answer on Stackoverflow
Solution 4 - JavaRobert KlemmeView Answer on Stackoverflow
Solution 5 - JavaMateusz DymczykView Answer on Stackoverflow
Solution 6 - JavaFlorian ReischlView Answer on Stackoverflow
Solution 7 - JavaJatinView Answer on Stackoverflow
Solution 8 - JavaSunnyView Answer on Stackoverflow
Solution 9 - JavaJollyView Answer on Stackoverflow
Solution 10 - JavaRyanView Answer on Stackoverflow
Solution 11 - JavaVignesh RajaView Answer on Stackoverflow
Solution 12 - JavaPalView Answer on Stackoverflow