ArrayList forEach(Consumer super action) method in java

Let’s learn ArrayList forEach(Consumer<? super E> action) method in java.

ArrayList forEach(Consumer super action) method in java

forEach(Consumer<? super E> action) method of ArrayList class performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Syntax:

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

Parameters:

action The action to be performed for each element.

Throws:

NullPointerException – if the specified action is null.

Also read – ArrayList in java

Now let’s see example on ArrayList forEach(Consumer<? super E> action) method.

import java.util.ArrayList;
public class ArrayListForEachMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(10);
      al.add(50);
      al.add(20);
      al.add(82);
      al.add(75);
      // print numbers using forEach method of ArrayList
      al.forEach((n) -> System.out.println(n));
   }
}


Output:

10
50
20
82
75


Let’s see another example.

import java.util.ArrayList;
public class ArrayListForEachMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> colors = new ArrayList<String>();
      colors.add("red");
      colors.add("blue");
      colors.add("green");
      colors.add("yellow");
      System.out.println("list of colors: ");
      // forEach method of ArrayList
      colors.forEach((n) -> System.out.println(n));
   }
}


Output:

list of colors:
red
blue
green
yellow