How to loop collection using Iterator object?

I show you three ways to loop collection using Iterator object. Hope you like and choose one to implement for your code. Although there are other ways to do but i recommend these ways for you.

Iterate via “iterator loop”
The hasNext() method returns true if the iteration has more elements. The next() method returns the next element in the iteration. Below example shows how to iterate through an ArrayList.

Iterate via “For each to loop”
It is mainly used to traverse collection and array. Using for-each loop will eliminate the possibility of bugs and makes the code more readable.

Iterator via “collection stream”
It returns a sequential Stream with this collection as its source and performs an action for each element of this stream. The Stream is supported in JDK 8.

Output

Banana
Apple
Orange
Kiwi
Mango

Leave a Comment

*

Please share it if you found this useful
Hide Buttons