Java Reference
In-Depth Information
Using the forEach() Method
The
Iterable
interface contains a new
forEach(Consumer<? super T> action)
method that you can use in all
collection types that inherit from the
Collection
interface. The method iterates over all elements and applies the action.
It works similar to the
forEachRemaining(Consumer<? super E> action)
method of the
Iterator
interface with a
difference that the
Iterable.forEach()
method iterates over all elements whereas the
Iterator.forEachRemaining()
method iterates over the elements in the collections that have not yet been retrieved by the
Iterator
.
The
forEach()
method is available in all collection types that inherit from the
Collection
interface. Listing 12-4
shows how to use the
forEach()
method to print all elements of a list of strings. Notice that using the
forEach()
method is the most compact way of iterating over elements of a collection.
■
the
Iterator
is the fundamental (and a little cumbersome) way of iterating over elements of a collection. it has
existed since the beginning. all other ways, such as the for-each loop, the
forEach()
method, and the
forEachRemaining()
method, are syntactic sugar for the
Iterator
. internally, they all use an
Iterator
.
Tip
Listing 12-4.
Using the forEach() Method of the Iterable Interface to Iterate Over Elements of a List
// ForEachMethod.java
package com.jdojo.collections;
import java.util.ArrayList;
import java.util.List;
public class ForEachMethod {
public static void main(String[] args) {
// Create a list of strings
List<String> names = new ArrayList<>();
// Add some names to the list
names.add("Ken");
names.add("Lee");
names.add("Joe");
// Print all elements of the names list
names.forEach(System.out::println);
}
}
Ken
Lee
Joe