Java Utility Library

Java ArrayList - forEach() Method



The java.util.ArrayList.forEach() method is used to perform the given action for each element of the iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

Syntax

public void forEach(Consumer<? super E> action)

Here, E is the type of element maintained by the container.


Parameters

action Specify the action to be performed for each element.

Return Value

void type.

Exception

Throws NullPointerException, if the specified action is null.

Example:

In the example below, the java.util.ArrayList.forEach() method is used to print each elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating the ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    System.out.println("MyList contains: ");
    MyList.forEach((n) ->  System.out.println(n)); 
  }
}

The output of the above code will be:

MyList contains: 
10
20
30
40
50

Example:

In the example below, the java.util.ArrayList.forEach() method is used to print string elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<String> MyList = new ArrayList<String>();

    //populating the ArrayList
    MyList.add("UK");
    MyList.add("USA");
    MyList.add("IND");

    System.out.println("MyList contains: ");
    MyList.forEach(System.out::println); 
  }
}

The output of the above code will be:

MyList contains: 
UK
USA
IND

❮ Java.util - ArrayList