Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

How to get the current loop index when using Iterator?

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?

Upvotes: 128

Views: 232422

Answers (11)

Paul
Paul

Reputation: 1519

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

Upvotes: 151

Jatin
Jatin

Reputation: 709

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.

Upvotes: 3

Sunny
Sunny

Reputation: 7604

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.

        }

Upvotes: 3

Vignesh Raja
Vignesh Raja

Reputation: 8751

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.

Upvotes: 1

Robert Klemme
Robert Klemme

Reputation: 2179

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);
}

Upvotes: 25

Jolly
Jolly

Reputation: 19

See here.

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

Upvotes: 1

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

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

Upvotes: 13

Ryan
Ryan

Reputation: 2008

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

Upvotes: 1

Chris Diver
Chris Diver

Reputation: 19822

Use your own variable and increment it in the loop.

Upvotes: 104

Tom Clift
Tom Clift

Reputation: 2395

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

Upvotes: 31

Florian Reischl
Florian Reischl

Reputation: 3856

Use an int and increment it within your loop.

Upvotes: 4

Related Questions