Java forEach loop


The forEach loop in Java is a control structure designed to simplify the iteration over collections and arrays. It is a part of the Java Collections Framework and was introduced in Java 8. This loop allows you to execute a block of code for each element in a collection, providing a more readable and concise syntax compared to traditional loops.

Syntax of the forEach Loop

The forEach method is called on a collection (like a list, set, or map) and accepts a lambda expression or a method reference as a parameter. The syntax looks like this:

collection.forEach(element -> { // Block of code to be executed for each element });

Example of a forEach Loop

Here’s an example demonstrating how to use the forEach loop to print elements of a list:

import java.util.ArrayList; import java.util.List; public class ForEachLoopExample { public static void main(String[] args) { // Create a list of strings List<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.add("Date"); // Using forEach to iterate over the list fruits.forEach(fruit -> { System.out.println("Fruit: " + fruit); }); } }

Explanation

  1. Collection Initialization: An ArrayList of strings called fruits is created and populated with fruit names.
  2. forEach Method: The forEach method is called on the fruits list, and a lambda expression is passed as an argument.
  3. Lambda Expression: The expression fruit -> { System.out.println("Fruit: " + fruit); } defines the action to be performed for each element in the list. Here, fruit represents the current element being processed.

Output

The output of the above program will be:

Fruit: Apple Fruit: Banana Fruit: Cherry Fruit: Date

Important Points

  • Simplicity: The forEach loop eliminates the need for boilerplate code such as index management or iterators, making the code cleaner and easier to read.
  • Lambda Expressions: Java 8 introduced lambda expressions, which provide a way to implement functional interfaces (interfaces with a single abstract method) and can be used as the parameter for the forEach method.
  • Non-Modifiable: If you modify the collection while iterating through it using forEach, it can throw a ConcurrentModificationException. It's advisable to avoid such modifications within the loop.

Example with a Map

You can also use the forEach method with a Map, as shown in the following example:

import java.util.HashMap; import java.util.Map; public class MapForEachExample { public static void main(String[] args) { // Create a map of fruit names and their colors Map<String, String> fruitColors = new HashMap<>(); fruitColors.put("Apple", "Red"); fruitColors.put("Banana", "Yellow"); fruitColors.put("Grape", "Purple"); // Using forEach to iterate over the map fruitColors.forEach((fruit, color) -> { System.out.println(fruit + " is " + color); }); } }

Output

The output will be:

Apple is Red Banana is Yellow Grape is Purple

Summary

The forEach loop is a powerful and expressive way to iterate over collections in Java, making the code easier to read and maintain. Its integration with lambda expressions enhances its usability, enabling functional programming styles in Java. Understanding how to use the forEach method effectively is essential for modern Java development.