Java ArrayList forEach() Method Tutorial

In this section, we will learn what the ArrayList forEach() method is and how to use it in Java.

What is Java ArrayList forEach() Method?

The Java ArrayList forEach() method is used to run a set of instructions for every element of an ArrayList object.

Note: using this method, you can’t change the elements of a list object! Basically, this method can just take the elements of a list and run a set of instructions based on it.

Java ArrayList forEach() Method Syntax:

arraylist.forEach(Consumer<E> action)

forEach() Method Parameters:

The forEac() method takes one argument.

This argument is a reference to a method that we want to execute it for each element in the target list object.

Now we can create this argument method with lambda expression or use an already existed instance or static method.

Note: the reference method should take only one argument that is of the same type as the elements of the target list object and it should not return a value.

forEach() Method Return Value:

The return value of this method is void.

forEach() Method Exceptions:

The method does not throw an exception.

Example: using ArrayList forEach() method

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

public class Main {

    public static void main(String[] args){
        List<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Six");
        list.add("Four");
        list.add("Five");
        list.add("Six");

       list.forEach(e->{
         System.out.println(e);
       });
    }
}

Output:

One

Two

Three

Six

Four

Five

Six

Leave a Reply