Loop Java List using iterator or for loop

 

In this post, we will see different ways to loop List in java like using iterator and for loop.

 

Using Iterator –

In this above example, we have created an object of ArrayList with String instances.

Then added values to List using add() method

Iterator() will return the elements and assign to iterator object, this object will call available methods to play with each elements from the collection (i.e List).

Iterator.hasNext() method will return true if the iteration has next value, and next() method will return the next value in the iteration.

 

Using advance for loop –

String str will hold each value from the List myList and display the value.

 

Using for loop with index –

myList.size() returns the no. of Strings present in the List and we loop based on the size

 

For more core Java related posts, refer Java topics

 

Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *