In this post under Java Collections, I will show with example an api provided in “Arrays” class that will populate an array with different element.
We are talking about “Arrays” class static method “setAll”. It takes two arguments
1) the array to be populated
2) a function that will generate the elements that are to be inserted in the array
For our example I will use an double array and fill it completely with different numbers.
Below is the complete main class for your reference
Main class
package core.collection;
import java.util.Arrays;
import java.util.Random;
public class ArraysSetAllDemo {
public static void main(String[] args) {
double[] doubleArray = new double[10];
String result = Arrays.toString(doubleArray);
System.out.println("Before modification: " + result);
Random random = new Random();
Arrays.setAll(doubleArray, i -> {
int value = i * random.nextInt(10);
return (double)value;
});
result = Arrays.toString(doubleArray);
System.out.println("After modification: " + result);
}
}
In the above code, at line 8, I create an double array of size 10.
At line 12, I am calling “Arrays” class static method “setAll” passing two arguments, the double array and a function instance that will generate different numbers.
The function is of type “java.util.function.IntToDoubleFunction”. This function will take an integer as an argument and returns a double. The integer argument represents a particular position in the array.
As a result of the call at line 12, all the 10 slots of the array “doubleArray” are set to random numbers of type “double”.
They are other overloaded version of “setAll” method. Please refer to javadoc for more info.
In this way we can use “setAll” static method.