How to determine the last element when using an iterator?

I like to use a for loop with an iterator principle like

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

Question: How to determine if the current item is the last?

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

+7
source share
3 answers

In fact, the Iterator#hasNext returns a logical definition if the iterator returns another element using the next method.

The iteration can be put as follows:

 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 } 
+8
source

Just use the hasNext method.

 if(!iterator.hasNext()) { // this is the last element } 

Usually we iterate using an Iterator like this:

 while(iterator.hasNext()) { Object obj = iterator.next(); } 
+5
source

This is not possible with an improved loop without maintaining your own counter. Honestly, this is my deciding factor when I choose which type of loop to use.

When using Iterator , you have access to the hasNext() method, which will return false when you process the last element.

+3
source

All Articles