#
forEach method (for Collections)
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.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
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);
});
}
}
Info
- As you can see "forEach" method is easy to use, and it is very useful.
- This method is added to the Iterable interface, so automatically to List, Set, Queue interfaces.