# forEach method (for Collections)

In 
Published 2022-12-03

This tutorial explains to you how to use forEach method in Java (for Collections). We have an example for you as well.

Before Java 8 this feature wasn't available.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

From the base application downloaded from Spring Initializr, I updated the main class as below:

DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class, args);

		//Create and define a Collection (List)
		ArrayList<String> carList = new ArrayList<>();

		// safe to use with multiple threads
		carList.add("Audi");
		carList.add("Renault");
		carList.add("Peugeot");
		carList.add("Dacia");

		for (String c : carList) {
			System.out.println("car= " + c);
		}
		
		// This is forEach method usage
		carList.forEach( x-> {
			System.out.println("forEach/ car= " + x);
		});

	}
}