Arrays.parallelPrefix(long[], LongBinaryOperator) in Java

Arrays.parallelPrefix(long[], LongBinaryOperator): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.parallelPrefix(long[] array, LongBinaryOperator op)

This method takes two arguments one of type long array and the other of type LongBinaryOperator as its parameters. This method cumulates, in parallel, each element of the given array in place,using the supplied function.

Parameters: Two parameters are required for this method.

array: the array, which is modified in-place by this method.

op: a side-effect-free, associative function to perform the accumulation.

Throws:

NullPointerException - if the specified array or function is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;
import java.util.function.LongBinaryOperator;

public class ArraysparallelPrefixlong {
    public static void main(String[] args) {

        long array[] = { 1, 2, 3, 4 };

        LongBinaryOperator sum = (d1, d2) -> d1 + d2;
        Arrays.parallelPrefix(array, sum);

        System.out.println(Arrays.toString(array));
    }
}

Output:

[1, 3, 6, 10]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.function.LongBinaryOperator;

public class ArraysparallelPrefixlong {
    public static void main(String[] args) {

        long array[] = null;

        LongBinaryOperator sum = (d1, d2) -> d1 + d2;
        Arrays.parallelPrefix(array, sum);

        System.out.println(Arrays.toString(array));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "array" is null at java.base/java.util.Arrays.parallelPrefix(Arrays.java:1433)


No comments:

Post a Comment