ArrayList.forEach(Consumer) in Java

ArrayList.forEach(Consumer<? super E>): This method is available in java.util.ArrayList class of Java.

Syntax:

void java.util.ArrayList.forEach(Consumer<? super Integer> action)

This method takes one argument. This method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Parameters: One parameter is required for this method.

action: The action to be performed for each element.

Throws:

1. NullPointerException - if the specified action is null

Approach 1: When no exceptions

Java

import java.util.ArrayList;

public class ArrayListforEach {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.forEach((n) -> System.out.print(n + " "));
    }
}

Output:

1 2 3 

Approach 2: NullPointerException 

Java

import java.util.ArrayList;

public class ArrayListforEach {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.forEach(null);
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.ArrayList.forEach(ArrayList.java:1506)


No comments:

Post a Comment