Java Reference
In-Depth Information
Arrays
.
asList
(
"One"
,
"Two"
,
"Three"
);
c
.
forEach
(
s
->
System
.
out
.
println
(
s
));
}
}
Declare a
Collection
(a
Collection
is an
Iterable
).
Variable argument lists
for how this arbitrary argument list becomes an array).
for a discussion of how s→System.out.println(s) gets mapped to a
Consumer
interface
implementation without your even having to import this interface).
This style of iteration—sometimes called “internal iteration”—inverts the control from
the traditional
for
loop; the collection is in charge of when and how the iteration works.
Java “foreach” loop (Java 5)
The “foreach” loop syntax is:
for (Type var : Iterable<Type>) {
// do something with "var"
}
This is probably the most common style of loop in modern Java code. The
Iterable
can
be an array, or anything that implements
Iterable
(the
Collection
implementations are
included in this).
This style is used throughout the topic, and is discussed a bit more in
Java 5 foreach loop
.
java.util.Iterator (Java 2)