Example of the foreach loop in Java

The foreach loop (called "enhanced for loop or advanced for loop") has been integrated since Java 5, is equivalent to java.util.Iterator. So, when reading an element, one by one in order, the foreach loop is the right choice, because it is more convenient.

Foreach syntax

The foreach loop is used to iterate through arrays as well as collections of objects.

for(variable type:  Table | collection){
.
.
}
Example:

for(String s : listString) {
System.out.println(s);
}

Traversing an array with foreach in java

public class Loops {
public static void main(String[] args) {
String[] tstring = {"aa","ab","ac","ad","ae"};
for(String s: tstring)
System.out.println(s);
}
}
Output:

aa
ab
ac
ad
ae

Object Collection Path with foreach

public class Parcours_List_foreach {
public static void main( String[] args) {
ArrayList arraylist = new ArrayList();
arraylist.add("e1");
arraylist.add("e2");
arraylist.add("e3");
arraylist.add("e4");

for(String s : arraylist){
System.out.println(s);
}
}
}
Runtime:

e1
e2
e3
e4
Note:  There are situations where you need to use Iterator directly, for example, deleting an item using foreach may cause an exception. ConcurrentModificationException.
Example:

Iterator iterator = list.iterator(); 
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
References:
JavaDoc: The For-Each Loop

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel ! J'ai enfin compris comment utiliser Apache POI correctement.

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

Merci Jean ! N'hésitez pas si vous avez des questions.