How to get the current loop index when using Iterator?

iterate list of list in java
iterator get index c++
how to iterate list inside list in java 8
java iterator
getting index of iterator
get array index from iterator
iterate list of objects in java 8
for loop get current index java

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?

Use your own variable and increment it in the loop.

How to Access the Index of the Current Element in a Modern For Loop, With C++98, iterators came along, and allowed to write this (if we How can we use a modern for loop and get access to the index of the  For loops have evolved over the years, starting from the C-style iterations to reach the range-based for loops introduced in C++11.. But the later, modern, versions of the for loop have lost a feature along the way: the possibility to access the index of the current element in the loop.

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: " +;

Make sure you call the nextIndex BEFORE you actually get the next().

3 Examples to Loop Through a List in Java 8, Now the question is whether should you use the Iterator or enhanced for loop, or the forEach() With the enhanced for loop, you can not modify selective objects as you don't have any index with you. System.out.println("Iterating List in Java Hi Brian Gideon - definitely agree (this was a few years ago and I was far less experienced at the time). However, while Dictionary isn't indexable, an iteration of Dictionary does traverse it in a particular order (i.e. an Enumerator is indexable by the fact it yields elements sequentially).

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

C++ : How to find an element in vector and get its index , in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method. Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter. Note: it is a common name for a container iterator, std::container_type::iterator it;. Share a link to this answer. improve this answer. edited Nov 30 '18 at 22:35. 50 silver badges. 88 bronze badges.

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 =;
    System.out.println(it.previousIndex() + ": " + s);

LinkedList listIterator() Method in Java, Review different ways to iterate through a List in Java. The update clause is used to modify the current state of the index variable, increasing it interface, all classes that implement Iterable have the forEach function added. Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ). For collections that implement List, you can also obtain an iterator by calling ListIterator.

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

Ways to Iterate Over a List in Java, Java 8 Streams are not collections and elements cannot be accessed using their indices, but there are still a few tricks to make this possible. boolean hasNext(): It returns true if Iterator has more element to iterate. Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element. void remove(): It removes the current element in the collection. This method throws ‘IllegalStateException’ if this function is called before next( ) is invoked.

How to Iterate Over a Stream With Indices, Before you can access a collection through an iterator, you must obtain one. Each of the Have the loop iterate as long as hasNext( ) returns true. Returns the index of the previous element. Removes the current element from the list. You can use an iterator to manually loop over the iterable it came from. A repeated passing of iterator to the built-in function next()returns successive items in the stream. Once, when you consumed an item from an iterator, it’s gone. When no more data are available a StopIteration exception is raised.

Java - How to Use Iterator?, Order of operations when using a foreach loop: the row index (based on a simple counter that you provide), or can simply return null. If you have a custom iterator that may throw an exception in it's current() method, there is no way to catch  You can alternatively use get_first( ) as in a Form view there is 1 BOL entity only. If you are in table view then,get_current gives the current entity. If you want the next row then get_next ( ) or you can loop at the collectio_wrapper and get the corresponding row using index.

Iterator - Manual, For example, the idea "Go five steps to the east" could be expressed this way as a loop: If present, the update expression incrementExpression is executed. With each iteration, the loop increments n and adds that value to x . iterates through the elements in an array until it finds the index of an element  Another way to iterate with indices can be done using zipWithIndex () method of StreamUtils from the proton-pack library (the latest version can be found here ). First, you need to add it to your pom.xml: <groupId>com.codepoetics</groupId> <artifactId>protonpack</artifactId> <version>1.13</version> Now, let's look at the code:

  • possible duplicate of Is there a way to access an iteration-counter in Java's for-each loop?
  • @finnw I do not think that they are duplicate. This question is asking using Iterator, the other is using for-each loop. Both questions are solved by similar approach, so the answers are duplicate not the question.
  • But also see @mateusz-dymczyk suggestion about it.nextIndex(). Useful when the collection is a List.
  • Thanks for mentioning 'Make sure you call the nextIndex BEFORE you actually get the next()'
  • Thanks, I didn't know about this before. The caution I would make is that ListIterator is bidirectional whereas Iterator is unidirectional. As long as you avoid moving back and forth with what is effectively a cursor, then you should be safe.
  • If you create the iterator yourself you can use a ListIterator as well and do not need the separate int variable.
  • If you use a 'static import' for Arrays.asList then you can just write asList("zero", "one", "two")
  • that is exactly the way i did it before i read the answer of Paul. I would strongly discourage your way, because I don't see any advantage to it. Do you think there is an advantage (except for the one mentioned). Why didn't you use a for-each loop? Defining the Iterator explicitely is not necessary, if you use your own variable.
  • @progressive_overload just if you need an Iterator (as per question, e.g. to pass to library), which the example doesn't show. In this example you have a variable outside the loop and need to be careful to call #next once. In Paul's example there are no variables outside the loop, but you need to be careful to call #next and #nextIndex together once (and in practice, if used more than once, they would be pulled into local variables, which that example doesn't show).
  • Calling indexOf() will require an additional scan of the device list. It will be faster to simply increment a local counter.
  • agreed. this is not the most efficient solution.
  • Looks like you updated the example to be more efficient.
  • The interface Iterator has NOT nextIndex() method. You need to explicitly use a ListIterator for that, but the OP questioned specifically about Iterator.
  • Actually, your code is off by one because it attempts to display the index AFTER calling