Java 8: forEach loop

  Java Features     Java 5     Java 7     Java 8  
Java 8 features
 Lambda expressions |   Method references |   Default methods |   forEach loop |   By date 

Before you start to learn this Java 8 feature, I would recommend you first to read the feature Lambda expressions.

Example 1: forEach loop using lambda expression

What is written to the standard output as the result of executing the following code?

import java.util.ArrayList;
import java.util.List;

public class Loop
{
  public static void main(String[] args)
  {
    List<String> carList = new ArrayList<String>();
    carList.add("Porsche");
    carList.add("Ferrari");
    carList.add("Bugatti");
    carList.add("Mercedes-Benz");
    carList.add("Lamborghini");
    // using forEach with lambda expression
    carList.forEach(car -> System.out.println(car));
  }
}
Author: Sar Maroof

Answer explanation

The answer is:

Porsche
Ferrari
Bugatti
Mercedes-Benz
Lamborghini





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *