Java 8 forEach() Method

Last Updated : 28 Jun 2026

Java 8 forEach() method defined in Iterable interface. It is used to iterate over collections such as Sets, Lists, and Maps in a readable and concise way. It was introduced as part of the functional programming features in Java 8, allows us to directly pass actions such as Method references or Lambda expressions. Instead of writing long loops, we can use forEach() along with a lambda expression to perform operations on each element.

Syntax:

  • default:The default keyword means the method has a default implementation inside the interface.
  • void: The void keywordrepresents the return type of the method. The forEach() method does not return any value; it only performs an action on each element.
  • forEach:It is the method name. It indicates that the method performs an operation on each element of the collection.
  • (Consumer<? super T> action): It is a parameter of the method. It is a functional interface belongs to the java.util.function package. It accepts an argumentand returns no result. We usually pass a lambda expression

Example: Iterating Over List

The following Java program demonstrates how to use Java 8's forEach() method with a lambda expression to iterate through an ArrayList.

Java

import java.util.ArrayList;  
import java.util.List;  
public class Main {  
    // main method
    public static void main(String[] args) {  
        List gamesList = new ArrayList(); // Creating a new ArrayList to store games  
        // Adding games to the list  
 gamesList.add("Football");  
        gamesList.add("Cricket");  
        gamesList.add("Chess");  
        gamesList.add("Hockey");  
        // Printing a separator  
        System.out.println("------------Iterating by passing lambda expression--------------");  
        // Iterating over the list using forEach and printing each element using a lambda expression  
        gamesList.forEach(game -> System.out.println(game));  
    }  
}  
Compile and Run

Output:

------------Iterating by passing lambda expression--------------
Football
Cricket
Chess
Hocky

Example: Iterating Over Map

The following Java program demonstrates how to use a HashMap and the forEach() method with a lambda expression to iterate through all key-value pairs.

Java

import java.util.HashMap;  
import java.util.Map;  
public class Main {  
     // main method
    public static void main(String[] args) {    
        // creating a HashMap
        Map map = new HashMap<>();
        map.put("A1", 110);
        map.put("B1", 210);
        map.put("C1", 310);
        map.put("D1", 410);
        map.put("E1", 510);
        map.put("F1", 610);
      // for each using lambda
      map.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v)); 
    }  
}  
Compile and Run

Output:

Key : A1, Value : 110
Key : F1, Value : 610
Key : E1, Value : 510
Key : D1, Value : 410
Key : C1, Value : 310
Key : B1, Value : 210

Example: Using forEach() Method with Consumer Interface

This Java program demonstrates how to use a Consumer functional interface with both a List and a Stream to convert strings into their hexadecimal character representations.

Java

import java.util.function.Consumer;
import java.util.*;
import java.util.stream.Stream;
public class Main {
    // main method
    public static void main(String[] args) {
        List list1 = Arrays.asList("def", "Python", "Java");
        Stream stream1 = Stream.of("def", "Python", "Java");
        // convert a String to a Hexadecimal
        Consumer displayTextInHexConsmer = (String s) -> {
            StringBuilder sbObj = new StringBuilder();
            for (char ch : s.toCharArray()) {
                String h = Integer.toHexString(ch);
                sbObj.append(h);
            }
            System.out.print(String.format("%n%-10s:%s", s, sbObj.toString()));
        };
        // passing a Consumer
        list1.forEach(displayTextInHexConsmer);
        stream1.forEach(displayTextInHexConsmer);
    }
}
Compile and Run

Output:

def       :646566
python    :707974686f6e
Java      :6a617661
def       :646566
Python    :707974686f6e
Java      :6a617661

Example: Using forEach() with Method Reference

In this example, the forEach() method uses a method reference instead of a lambda expression.

Java

import java.util.List; 
import java.util.ArrayList;  
public class Main {  
    public static void main(String[] args) {  
        List gamesList = new ArrayList();  
       gamesList.add("Football");  
        gamesList.add("Cricket");  
        gamesList.add("Chess");  
        gamesList.add("Hockey");  
        //iterating over list
        gamesList.forEach(System.out::println);  
    }  
}  
Compile and Run

Output:

Football
Cricket
Chess
Hockey

Java forEach() Method Vs. Traditional Loop

FeatureforEach() MethodTraditional Loop (for, while)
ParadigmIt is declarative (we state what to do).It is imperative (we state how to do it).
Control FlowIt does not support break or continue statement.It supports break, continue, and return statement.
Data ScopeIt creates a new block scope for each callback.It shares the same scope across all iterations.
Asynchronous BehaviorIt does not wait for async/await promises.It seamlessly supports async/await step-by-step.
ApplicabilityIt is specific to arrays or collections.It is used for general purpose. It can run without a collection.
PerformanceIt is slightly slower due to function call overhead.It is faster, highly optimized by compilers.