Java Utility Library

Java Arrays - setAll() Method



The java.util.Arrays.setAll() method is used to set all elements of the specified array, using the provided generator function to compute each element. If the generator function throws an exception, it is relayed to the caller and the array is left in an indeterminate state.

Syntax

public static void setAll(double[] array,
                          IntToDoubleFunction generator)

Parameters

array Specify array to be initialized.
generator Specify a function accepting an index and producing the desired value for that position.

Return Value

void type.

Exception

Throws NullPointerException, if the generator is null.

Example:

In the example below, the java.util.Arrays.setAll() method is used to set all elements of the given array using the given generator function.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a double array
    double Arr[] = {1, 2, 3, 4, 5};

    //printing array
    System.out.print("Arr contains:"); 
    for(double i: Arr)
      System.out.print(" " + i);

    //set all elements of the array to the square
    //of itself using generator function
    Arrays.setAll(Arr, e->{
      return Arr[e]*Arr[e];
    });

    //printing array
    System.out.print("\nArr contains:"); 
    for(double i: Arr)
      System.out.print(" " + i);
  }
}

The output of the above code will be:

Arr contains: 1.0 2.0 3.0 4.0 5.0
Arr contains: 1.0 4.0 9.0 16.0 25.0

❮ Java.util - Arrays