Consider:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for
loop look like without using the for each syntax?
An alternative to forEach in order to avoid your "for each":
Variant 1 (plain):
Variant 2 (parallel execution (faster)):
In Java 8, they introduced forEach. Using it List, Maps can be looped.
Loop a List using for each
or
Loop a Map using for each
or
Here's an equivalent expression.
Note that if you need to use
i.remove();
in your loop, or access the actual iterator in some way, you cannot use thefor ( : )
idiom, since the actual iterator is merely inferred.As was noted by Denis Bueno, this code works for any object that implements the
Iterable
interface.Also, if the right-hand side of the
for (:)
idiom is anarray
rather than anIterable
object, the internal code uses an int index counter and checks againstarray.length
instead. See the Java Language Specification.The Java "for-each" loop construct will allow iteration over two types of objects:
T[]
(arrays of any type)java.lang.Iterable<T>
The
Iterable<T>
interface has only one method:Iterator<T> iterator()
. This works on objects of typeCollection<T>
because theCollection<T>
interface extendsIterable<T>
.