Java Reference
In-Depth Information
// Remove the name if it is two characters
if (name.length() == 2) {
nameIterator.remove();
}
}
The
forEachRemaining()
method is new to Java 8 and takes an action on each element of the collection that has
not been accessed by the iterator yet. The action is specified as a
Consumer
. You can use the following snippet of code
to print all elements of a list:
List<String> names = get a list;
// Get an iterator for the list
Iterator<String> nameIterator = names.iterator();
// Print the names in the list
nameIterator.forEachRemaining(System.out::println);
The code uses method reference
System.out::println
as a
Consumer
for the
forEachRemaining()
method.
Notice that using the
forEachRemaining()
method helps shorten the code by eliminating the need for a loop
using the
hasNext()
and
next()
methods. Please refer to Chapter 5 for more on using the
Consumer
interface and
method references.
Listing 12-2 contains a complete program that uses an iterator and the
forEachRemaining()
of the iterator to
print all elements of a list on the standard output. The program has combined the steps to obtain the iterator and call
its
forEachRemaining()
method call into one statement.
Listing 12-2.
Using an Iterator to Iterate Over Elements of a List
// NameIterator.java
package com.jdojo.collections;
import java.util.ArrayList;
import java.util.List;
public class NameIterator {
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.iterator()
.forEachRemaining(System.out::println);
}
}