Write a Java Program to Iterate over ArrayList using Lambda Expression

In Java, an ArrayList is an implementation of the List interface that allows for dynamic resizing and supports various operations like adding, removing, and accessing elements.

In this tutorial, we will learn how to iterate over an ArrayList using a Lambda Expression.


Lambda expressions were introduced in Java 8 and provide a concise way to represent anonymous functions.

They are particularly useful for iterating over collections and performing operations on their elements.

Before Java 8, iterating over a collection involved writing a for loop and accessing each element one by one.

With Lambda expressions, this process is much simpler and cleaner.

To iterate over an ArrayList using a Lambda Expression, we will use the forEach() method that is available in the List interface.

The forEach() method takes a Consumer as an argument, which is a functional interface that represents an operation that takes in one argument and returns no result.

Let’s take a look at the code to understand how to use Lambda expressions to iterate over an ArrayList:

import java.util.ArrayList;

public class IterateArrayListWithLambda {

    public static void main(String[] args) {
        ArrayList<String> programmingLanguages = new ArrayList<>();
        programmingLanguages.add("Java");
        programmingLanguages.add("Python");
        programmingLanguages.add("C++");
        programmingLanguages.add("JavaScript");

        programmingLanguages.forEach((language) -> System.out.println(language));
    }
}

In this code, we first create an ArrayList called programmingLanguages and add four elements to it.

We then call the forEach() method on the ArrayList and pass in a lambda expression that prints out each element to the console.

The lambda expression (language) -> System.out.println(language) takes in one argument (the current element in the iteration) and prints it to the console using System.out.println().

When we run this program, we will see the following output:

Java
Python
C++
JavaScript

As we can see, the forEach() method iterates over the ArrayList and applies the lambda expression to each element in the list.


In conclusion, iterating over an ArrayList using a Lambda Expression is a powerful and concise way to perform operations on a collection’s elements.

With the forEach() method and lambda expressions, we can avoid writing complex loops and make our code more readable and maintainable.