Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if processing the last item in an Iterator?

Tags:

java

iterator

People also ask

Does iterator maintain order?

Iteration OrderThe order in which the elements contained in a Java Iterator are traversed depends on the object that supplies the Iterator . For instance, an iterator obtained from a List will iterate through the elements of that List in the same order the elements are stored internally in the List .

Does iterator next return the first element?

This has nothing to do with the position of the iterator. next() picks out and remembers the element at the pointer, then advances the pointer, then returns the remembered element. You're overthinking it. next() returns the next element in the sequence, starting with the first element.

Is there a next method in iterator?

The hasNext() method of ListIterator interface is used to return true if the given list iterator contains more number of element during traversing the given list in the forward direction.


You can check it just like you do in the while condition:

if ( ! iter.hasNext()) {
    // last iteration
    ...
}

If iter.hasNext() is false after iter.next() then it is the last item.

Happy coding.


This answer is not specific to an Iterator, but can be used for any iterating statement where you need to insert a separator between items. It doesn't need to know the current index nor does it need any condition.

String previousSeparator = "";
for (String value : collection) {
  System.err.println(previousSeparator + value);
  previousSeparator = ",";
}

Although other answers gave some ideas, I think it is better to add it without the condition and remove the last delimiter after the while loop terminates.