Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine last element when using an iterator?

Tags:

java

iterator

I love to use a for loop with the iterator principle, like

for(String s : collectionWithStrings)
    System.out.println(s + ", ");

Question: How can I determine if the current element is the last one?

With an own index like int = 0; i < collection.size(); i++ this is possible with i == collection.size() - 1, but not nice. Is it also possible to determine the last element with an iterator for the example above?

like image 863
John Threepwood Avatar asked Feb 05 '13 14:02

John Threepwood


People also ask

How do you find the iterator element?

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

Does iterator next return the first element?

next() returns the next element in the sequence, starting with the first element.

Does iterator have previous method?

The hasPrevious method returns true if the list iterator has more elements on traversing in the reverse direction. Otherwise, it returns false .

Which method removes the last elements returned by the iterator?

remove. Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next() .


1 Answers

Indeed, the Iterator#hasNext method returns a boolean determining if the iterator will return another element with the next method.

Your iteration can be put as this:

Iterator<String> iterator = collectionWithString.iterator();
while(iterator.hasNext()) {
    String current = iterator.next();
    // if you invoke iterator.hasNext() again you can know if there is a next element
}
like image 90
Fritz Avatar answered Oct 19 '22 23:10

Fritz