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?
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( ).
next() returns the next element in the sequence, starting with the first element.
The hasPrevious method returns true if the list iterator has more elements on traversing in the reverse direction. Otherwise, it returns false .
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() .
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
}
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