Java - Collections Traversing - for-each Loop

Introduction

You can use the for-each loop to iterate over elements of a collection.

The general syntax for the for-each loop is as follows:

Collection<T> yourCollection = // get a collection here;

for(T element : yourCollection) {
}

You can iterate over all elements of a list of string as follows:

List<String> names = // get a list;

// Print all elements of the names list using a for-each loop
for(String name : names) {
        System.out.println(name);
}

The following code uses the for-each loop to iterate over elements of a list of strings.

Demo

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    // Create a list of strings
    List<String> names = new ArrayList<>();

    // Add some names to the list
    names.add("Java");
    names.add("Javascript");
    names.add("Joe");

    // Print all elements of the names list
    for (String name : names) {
      System.out.println(name);/*from   ww w.  j ava 2 s  .  c  o m*/
    }
  }
}

Result

Limitation

You cannot use the for-each loop to remove elements from the collection.

The following code will throw a ConcurrentModificationException exception:

List<String> names = get a list;
for(String name : names) {
    // Throws a ConcurrentModificationException
    names.remove(name);
}

You cannot start for-each loop in the middle of the collection and you have no way to visit the previously visited elements.