Close

Java Collections - Arrays.parallelSetAll() Examples

Java Collections Java Java API 


Class:

java.util.Arrays

java.lang.Objectjava.lang.Objectjava.util.Arraysjava.util.ArraysLogicBig

Methods:

These methods set all elements of the specified array, in parallel, using the provided generator function to compute each element.

public static <T> void parallelSetAll(T[] array,
                                      IntFunction<? extends T> generator)
public static void parallelSetAll(int[] array,
                                  IntUnaryOperator generator)
public static void parallelSetAll(long[] array,
                                  IntToLongFunction generator)
public static void parallelSetAll(double[] array,
                                  IntToDoubleFunction generator)

Examples


package com.logicbig.example.arrays;

import java.util.Arrays;

public class ParallelSetAllExample {

public static void main(String... args) {
int[] arr = new int[10];

Arrays.parallelSetAll(arr, (index) -> 1 + index * 2);
System.out.println(Arrays.toString(arr));
}
}

Output

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]




Generator are executed in parallel, number of threads= available processor cores (8 on my machine):

package com.logicbig.example.arrays;

import java.time.LocalTime;
import java.util.Arrays;

public class ParallelSetAllExample2 {

public static void main(String... args) {
int[] arr = new int[10];
Arrays.parallelSetAll(arr, (index) -> {
System.out.println(LocalTime.now());
return 1 + index * 2;
});
System.out.println(Arrays.toString(arr));
}
}

Output

16:22:41.916
16:22:41.916
16:22:41.916
16:22:41.916
16:22:41.922
16:22:41.916
16:22:41.916
16:22:41.916
16:22:41.916
16:22:41.922
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]




package com.logicbig.example.arrays;

import java.util.Arrays;

public class ParallelSetAllExample3 {

public static void main(String... args) {
String[] arr = new String[10];
Arrays.parallelSetAll(arr, (index) -> Integer.toString(index + 1));
System.out.println(Arrays.toString(arr));
}
}

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]




See Also