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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With