Java - Collections Traversing - forEach() Method

Introduction

You can use forEach(Consumer<? super T> action) method to iterate through a collection.

The method iterates over all elements and applies the action.

forEach() method iterates over all elements whereas the forEachRemaining() method iterates over the elements in the collections that have not yet been retrieved by the Iterator.

forEach() method is available in all collection types that inherit from the Collection interface.

The following code uses the forEach() method to print all 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
    names.forEach(System.out::println);
  }/*from  w w w.j  a v a2s  .  com*/
}

Result