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 ).
Po pulate it with Arrays.asList , passing a literal array into the asList() method (see
Variable argument lists for how this arbitrary argument list becomes an array).
In voke the collection's forEach() method, passing a lambda expression (see Chapter 9
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)
The older Iterator is discussed in Using Iterators or Enumerations for Data-Independ-
ent Access .
 
 
 
Search WWH ::




Custom Search