top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java ArrayList forEach

Introduction

Before you understand the Java ArrayList forEach loop, you need to understand the ArrayList. It is a list used to manipulate and store collections of objects. It is a multipurpose paradigm that allows removing, adding, modifying, and retrieving elements within the list. To simplify the iteration process of the ArrayList in Java, we have the concept of the Java ArrayList forEach loop- also called the “enhanced for loop”. 

So what does this loop do? As the ArrayList is dynamic and needs a tedious index management system, this loop takes over managing the ArrayList. It offers a concise syntax and enhances code readability. forEach() in Java makes it easier and more efficient to traverse elements in the ArrayList. 

By combining the two efficient paradigms of ArrayLists and the forEach loop, developers streamline their code and achieve efficient data processing and manipulation results. 

Overview

The scope of this tutorial begins with the fundamentals of ArrayLists as a concept. It will dive deep into the forEach loop and its usage in ArrayLists. By the end of this tutorial, readers will have a solid understanding of how to utilize ArrayLists and the forEach loop together through sufficient Java ArrayList forEach example. So let's get started.

ArrayList forEach() method in Java

The Java ArrayList forEach() method performs iterations over each element in an ArrayList in Java. As each element passes the check, a user-specified/system-specified action is performed. forEach() in Java streamlines the iterations of items through the ArrayList, offering a concise and efficient way to process each element individually.

Here is an example of using the forEach() method of ArrayList in Java:

In the example above, we create an ArrayList called fruits and add some fruit names. Then, we demonstrate two ways to use the forEach() method to iterate over the elements of the list.

The first usage demonstrates the forEach() method with a lambda expression. Inside the lambda expression, we simply print each fruit using System.out.println(fruit).

The second usage demonstrates the forEach() method with a method reference (System.out::println). This syntax is equivalent to using a lambda expression that calls System.out.println() with the current element as the argument.

Code:

import java.util.ArrayList;


public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");


        // Using forEach() method with lambda expression
        System.out.println("Using forEach() method with lambda expression:");
        fruits.forEach(fruit -> System.out.println(fruit));


        // Using forEach() method with method reference
        System.out.println("\nUsing forEach() method with method reference:");
        fruits.forEach(System.out::println);
    }
}

Syntax of ArrayList forEach() in Java 

Here is the syntax for the forEach() method in Java:

void forEach(Consumer<? super E> action)

Let us now break down the syntax and discuss each component.

  • action: A functional interface representing the action to be performed on each element of the ArrayList. It accepts a single parameter of type E, where E is the type of elements in the ArrayList.

  • void: Since forEach() is a void method, it does not return any value.

  • Consumer: The forEach() method applies the specified action to each element in the ArrayList in the order they appear. The implementation of the Consumer functional interface defines the action. The Consumer functional interface accepts a single argument and performs an operation on it. In the case of forEach(), the consumer's accept() method is invoked for each element in the list.

Exceptions of ArrayList forEach() in Java

The forEach() method of ArrayList in Java does not throw any checked exceptions. However, if the action provided in the forEach() method throws an exception, it will be caught and wrapped in a RuntimeException. This means that any unchecked exceptions thrown by the action will be propagated, resulting in a RuntimeException being thrown.

Here is an example to demonstrate this:

We iterate over an ArrayList of integers in this program using the forEach() method. Inside the action provided by the lambda expression, we divide 10 by each number in the list. Since division by zero is not allowed, an ArithmeticException will occur when the number 0 is encountered.

To handle this exception, we wrap the forEach() method call in a try-catch block and catch the ArithmeticException. If an exception occurs within the forEach() method, it will be caught, and the corresponding error message will be printed.

Remember that this exception handling is specific to the action provided within the forEach() method. The forEach() method itself does not throw any checked exceptions, and any exceptions thrown by the action will be wrapped in a RuntimeException if they are unchecked exceptions.

Code:

import java.util.ArrayList;

public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);


        try {
            numbers.forEach(number -> {
                System.out.println(10 / number);
            });
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException occurred: " + e.getMessage());
        }
    }
}

Example 1: ArrayList forEach() in Java

Here is an example that showcases two different ways of defining actions using lambda expressions and method references within the forEach() method of ArrayList:

In this above example, we have an ArrayList called names that stores some names. We use the forEach() method to iterate over the elements of the list and perform specific actions.

First, we use a lambda expression name -> System.out.println(name) as the action. This lambda expression simply prints each name in the ArrayList to the console.

Next, we demonstrate the usage of a method reference by passing System.out::printlnUpperCase as the action. The printlnUpperCase method is defined in a separate StringUtils class, and it converts a given string to uppercase and prints it. The forEach() method will call this method for each name in the ArrayList, resulting in the uppercase names being printed to the console.

Code:

import java.util.ArrayList;

public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Alice");
        names.add("Bob");
        names.add("Emily");


        System.out.println("Names:");
        names.forEach(name -> System.out.println(name));


        // Using method reference
        System.out.println("\nNames in uppercase:");
        names.forEach(StringUtils::printlnUpperCase);
    }


    static class StringUtils {
        public static void printlnUpperCase(String str) {
            System.out.println(str.toUpperCase());
        }
    }
} 

Example 2: forEach() Method on ArrayList Which Contains a List of Numbers

Here is an example of using the forEach() method on an ArrayList that contains a list of numbers:

In the above program, we have an ArrayList called numberLists, which contains two separate lists of numbers.

We create two List<Integer> instances, list1 and list2, and add them to the numberLists ArrayList.

We then use the forEach() method on numberLists to iterate over each list. Within the outer forEach() iteration, we use another forEach() method to iterate over the numbers within each list. We print each number using System.out.print(), followed by a newline character using System.out.println(), to display each list of numbers on a separate line.

Code:

import java.util.ArrayList;
import java.util.List;


public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<List<Integer>> numberLists = new ArrayList<>();


        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        numberLists.add(list1);


        List<Integer> list2 = new ArrayList<>();
        list2.add(4);
        list2.add(5);
        list2.add(6);
        numberLists.add(list2);


        System.out.println("Numbers in the lists:");
        numberLists.forEach(list -> {
            list.forEach(number -> System.out.print(number + " "));
            System.out.println();
        });
    }
}

Example 3: forEach() Method on ArrayList Which Contains a List of Objects

Here is an example below of using the forEach() method on an ArrayList that contains a list of objects:

In this example, we have an ArrayList called personLists, which contains two lists of Person objects.

We create two List<Person> instances, list1 and list2, and add them to the personLists ArrayList.

We then use the forEach() method on personLists to iterate over each list. Within the outer forEach() iteration, we use another forEach() method to iterate over the Person objects within each list. We print each Person object using System.out.println() by relying on the toString() method overridden in the Person class.

Code:

import java.util.ArrayList;
import java.util.List;

public class upGradTutorials {
    public static void main(String[] args) {
        ArrayList<List<Person>> personLists = new ArrayList<>();


        List<Person> list1 = new ArrayList<>();
        list1.add(new Person("John", 25));
        list1.add(new Person("Alice", 30));
        personLists.add(list1);


        List<Person> list2 = new ArrayList<>();
        list2.add(new Person("Bob", 28));
        list2.add(new Person("Emily", 22));
        personLists.add(list2);


        System.out.println("Persons in the lists:");
        personLists.forEach(list -> {
            list.forEach(person -> System.out.println(person));
            System.out.println();
        });
    }
}


class Person {
    private String name;
    private int age;


    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }


    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

Java Stream forEachOrdered() Method in Java 8

The forEach() method provides a concise way to iterate over a collection and perform an action on each element. The forEachOrdered() method guarantees that the elements are processed in the order they appear in the stream.

Both methods offer different advantages depending on your use case. We use forEach() for unordered processing or when the order is not important, and we use forEachOrdered() when we need to maintain the encounter order of the elements.

Here's an example that showcases the forEach() method in Java 8 and the forEachOrdered() method in Java Stream:

In this example, we have a List called fruits containing different fruit names.

First, we demonstrate the usage of the forEach() method available in Java 8. It iterates over the elements of the list using a lambda expression (fruit -> System.out.println(fruit)) and prints each fruit name to the console. The order of the elements is not guaranteed.

Next, we showcase the forEachOrdered() method in the Java Stream API. This method is used on a stream of elements (fruits.stream()) and ensures that the elements are processed in the encounter order. Again, we use a lambda expression to print each fruit name to the console.

Code:

import java.util.ArrayList;
import java.util.List;

public class upGradTutorials {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");


        // Java 8 forEach() method
        System.out.println("Using forEach():");
        fruits.forEach(fruit -> System.out.println(fruit));


        // Java Stream forEachOrdered() method
        System.out.println("\nUsing forEachOrdered():");
        fruits.stream().forEachOrdered(fruit -> System.out.println(fruit));
    }
}

Conclusion

The ArrayList forEach() method in Java provides a convenient and streamlined approach to iterate over elements in an ArrayList. It eliminates manual index management and enhances code readability by offering a concise syntax. With forEach(), you can easily perform actions on each element of the ArrayList, making it ideal for processing data collections. 

This method simplifies complex operations and reduces the likelihood of errors with traditional for loops. By utilizing forEach() effectively, you can efficiently manipulate ArrayList elements and achieve greater code efficiency. Embrace this powerful method to enhance your Java programming skills and optimize your data handling capabilities.

FAQs

1. Why do we use forEach in Java?

It is a concept used to “traverse” the ArrayList or a particular data set. It benefits the code by eliminating all possible bugs and making it more concise, robust, and readable.

2. What is the primary difference between forEach and for loop?

While the forEach loop works inside a specified range or collection of data, the for loop is applicable globally and is not restricted to a specific list or collection elements alone. 

3. Can forEach transform elements in an array?

No, the Java forEach array method is primarily used to loop through the elements of the array. To transform them, you can use the MAP() function instead.  

Leave a Reply

Your email address will not be published. Required fields are marked *