Java Reference
In-Depth Information
How Shall I Iterate Thee? Let Me Enumerate the Ways
Problem
You need to iterate over some structured data.
Solution
Java provides many ways to iterate over collections of data. In newest-first order:
▪
Iterable.forEach
method (Java 8)
▪ Java “foreach” loop (Java 5)
▪
java.util.Iterator
(Java 2)
▪ Three-part
for
loop
▪ “while” loop
▪ Enumeration
Pick one and use it. Or learn them all and save!
Discussion
A few words on each of the iteration methods are given here.
Iterable.forEach method (Java 8)
The most recent iteration technique is the
Iterable.forEach()
method, added in Java 8.
This method can be called on any
Iterable
(unfortunately, the array class does not yet im-
plement
Iterable
), and takes one argument implementing the
functional interface
java.util.function.Consumer
. Functional Interfaces are discussed in
Chapter 9
, but here
is one example:
public
public class
class
IterableForEach
IterableForEach
{
public
public static
void
main
(
String
[]
args
) {
Collection
<
String
>
c
=
static
void