Arrays ParallelPrefix Cumulative Sums
Compute in-place cumulative sums with Arrays.parallelPrefix, which applies an associative operator over array prefixes using fork-join parallelism.
Code
import java.util.Arrays;
public class CumulativeUsage {
public static void main(String[] args) {
int[] hourlyBytes = {120, 340, 90, 210, 455, 30};
// 原地并行前缀和:index i 变成前 i+1 项之和
Arrays.parallelPrefix(hourlyBytes, Integer::sum);
System.out.println("cumulative: " + Arrays.toString(hourlyBytes));
// 前缀积:把逐期增长率累乘成复利系数
double[] growth = {1.02, 1.05, 0.98, 1.10};
Arrays.parallelPrefix(growth, (a, b) -> a * b);
System.out.println("compounded: " + Arrays.toString(growth));
// 与手写循环逐项等价(算子需满足结合律,否则并行分段结果不定)
int[] manual = {120, 340, 90, 210, 455, 30};
for (int i = 1; i < manual.length; i++) {
manual[i] += manual[i - 1];
}
System.out.println("matches manual loop: " + Arrays.equals(manual, hourlyBytes));
}
}What the code does
Arrays ParallelPrefix Cumulative Sums reduces to the class CumulativeUsage and the function main.
The one repetition in this snippet is the loop for (int i = 1; i < manual.length; i++).
Applying it
Signature: public static void main(String[] args)
The demo output is labeled (cumulative:, compounded:, matches manual loop:), so the output doubles as a step-by-step trace of what the file did.
Statements that matter
manual[i] += manual[i - 1];
Interactive Tools for This Topic
FAQ
- What does Arrays ParallelPrefix Cumulative Sums print when run?
- No setup needed: run the file and look for labeled lines like `cumulative:`, `compounded:`, `matches manual loop:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.