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 <T> void setAll(T[] array,
                              IntFunction<? extends T> generator)

Here, T is the type of elements in the array.


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[] = {1d, 2d, 3d, 4d, 5d};

    //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, i->{
      return Arr[i]*Arr[i];
    });

    //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