Arrays.parallelSetAll(double[], IntToDoubleFunction) in Java

Arrays.parallelSetAll(double[], IntToDoubleFunction): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.parallelSetAll(double[] array, IntToDoubleFunction generator)

This method takes two arguments one of type double array and the other of type IntToDoubleFunction as its parameters. This method set all elements of the specified array, in parallel, using the provided generator function to compute each element.

Note: If the generator function throws an exception, an unchecked exception is thrown from parallelSetAll and the array is left in an indeterminate state.

Parameters: Two parameters are required for this method.

array: array to be initialized.

generator: a function accepting an index and producing the desired value for that position.

Throws:

NullPointerException - if the generator is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;
import java.util.function.IntToDoubleFunction;

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

        double array[] = { 12, 34, 56, 78 };

        IntToDoubleFunction generator = intVal -> {
            double doubleVal = intVal;
            return doubleVal;
        };

        Arrays.parallelSetAll(array, generator);

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

Output:

[0.0, 1.0, 2.0, 3.0]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.function.IntToDoubleFunction;

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

        double array[] = { 12, 34, 56, 78 };

        IntToDoubleFunction generator = null;

        Arrays.parallelSetAll(array, generator);

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

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Arrays.parallelSetAll(Arrays.java:5254)


No comments:

Post a Comment