The forEach method for a collection

Starting with Java 8, we can invoke the forEach method on a collection and iterate through the contents of the collection. Let's compare the 7 and 8 versions of iterating over an array list of strings.

The following code, which is from Jave 7, fetches individual fruit names from the fruits list and prints it to the console:


List<String> fruits = Arrays.asList("Apples", "Oranges", "Bananas",
"Pears");
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}

A second alternative that you can use is as follows:

for (String fruit : fruits ){
System.out.println(fruit);
}

The example shown here does the same thing in Java 8 using lambda expressions:

fruits.forEach(i -> System.out.println(i));