Iterating over a List in Java

In this example, we will see five ways to iterate over a List in Java.

Consider the following list :

List<String> persons = Arrays.asList("Khadija", "Walid", "Hamouda", "Mariam");

 

1. “for” statement

for (int i = 0; i < persons.size(); i++) {
	String person = persons.get(i);
	System.out.println(person);
}

 

2. “enhanced for” statement

for (String person : persons) {
	System.out.println(person);
}

 

3.”while” statement

int i = 0;
while (i < persons.size()) {
	String person = persons.get(i);
	System.out.println(person);
	i++;
}

 

4. “do-while” statement

int j = 0;
do {
	String person = persons.get(j);
	System.out.println(person);
	j++;
} while (j < persons.size());

 

5. “iterator” statement

Iterator<String> itr = persons.iterator();
while (itr.hasNext()) {
	String person = itr.next();
	System.out.println(person);
}