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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

packagecom.javabycode.iterator;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

publicclassSampleCollectionIterator{

publicstaticvoidmain(Stringa[]){

List<String>fruitList=newArrayList<String>();

fruitList.add("Banana");

fruitList.add("Apple");

fruitList.add("Orange");

fruitList.add("Kiwi");

fruitList.add("Mango");

Iterator<String>iterator=fruitList.iterator();

while(iterator.hasNext()){

System.out.println(iterator.next());

}

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

packagecom.javabycode.iterator;

import java.util.ArrayList;

import java.util.List;

publicclassSampleCollectionIterator{

publicstaticvoidmain(Stringa[]){

List<String>fruitList=newArrayList<String>();

fruitList.add("Banana");

fruitList.add("Apple");

fruitList.add("Orange");

fruitList.add("Kiwi");

fruitList.add("Mango");

// iterate via "For each loop"

for(Stringfruit:fruitList){

System.out.println(fruit);

}

}

}

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.