Collections

Arrays parallelPrefix() in Java Code With Examples

Table of Contents

Program

import java.util.Arrays;
public class ArraysParrelelPrefix
{
	static int compute(int x,int y)
	{
		return x + y;
	}
	public static void main(String[] args)
		{
			System.out.println("1. Parallel Prefix From Index To Index :");
			int[] arr1 = { 1, 2, 3, 4, 5 };
			Arrays.parallelPrefix(arr1, (left, right) -> left * right);
			System.out.println(Arrays.toString(arr1));
			System.out.println("");
			System.out.println("2. Parallel Prefix Int Binary Opeerator :");
			int[] arr2 = { 1,2,3,4,5,6,7};	
			Arrays.parallelPrefix(arr2, (x,y)-> compute(x,y));
			Arrays.stream(arr2).forEach(e -> System.out.print(e + " "));
		}
}

Output

1. Parallel Prefix From Index To Index :
[1, 2, 6, 24, 120]

2. Parallel Prefix Int Binary Opeerator :
1 3 6 10 15 21 28 

Description

public static void parallelPrefix​(int[] array, IntBinaryOperator op)

Cumulates, in parallel, each element of the given array in place, using the supplied function.
For example if the array initially holds [2, 1, 0, 3] and the operation performs addition, then upon return
the array holds [2, 3, 3, 6]. Parallel prefix computation is usually more efficient than sequential loops
for large arrays.

Parameters:

array – the array, which is modified in-place by this method
op – a side-effect-free, associative function to perform the cumulation

Throws:

NullPointerException – if the specified array or function is null

public static void parallelPrefix​(int[] array, int fromIndex, int toIndex, IntBinaryOperator op)

Performs parallelPrefix(int[], IntBinaryOperator) for the given subrange of the array.

Parameters:

array – the array
fromIndex – the index of the first element, inclusive
toIndex – the index of the last element, exclusive
op – a side-effect-free, associative function to perform the cumulation

Throws:

IllegalArgumentException – if fromIndex > toIndex
ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > array.length
NullPointerException – if the specified array or function is null