Custom Collector With Combiner

Implement a custom Collector whose combiner folds two Welford accumulators, so parallel streams land on the same sample variance as the sequential run.

JavaData Integrity

Code

snippet
import java.util.stream.Collector;
import java.util.stream.Stream;

public class StreamingVariance {

    // Welford 累加器:count / mean / m2 三量,merge 负责把两段并行结果合并
    static final class Welford {
        private long count;
        private double mean;
        private double m2;

        void add(double x) {
            count++;
            double delta = x - mean;
            mean += delta / count;
            m2 += delta * (x - mean);
        }

        // combiner:两段子流的统计量无偏合并,merge 必须返回合并后的累加器
        Welford merge(Welford other) {
            if (other.count == 0) {
                return this;
            }
            long n = count + other.count;
            double delta = other.mean - mean;
            mean += delta * other.count / n;
            m2 += other.m2 + delta * delta * count * other.count / n;
            count = n;
            return this;
        }

        double sampleVariance() {
            return count < 2 ? Double.NaN : m2 / (count - 1);
        }
    }

    public static void main(String[] args) {
        Collector<Double, Welford, Double> variance = Collector.of(
                Welford::new, Welford::add, Welford::merge, Welford::sampleVariance);

        double sequential = Stream.of(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
                .collect(variance);
        double parallel = Stream.of(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0)
                .parallel()
                .collect(variance);
        System.out.println("sequential = " + sequential); // 32 / 7
        System.out.println("parallel   = " + parallel);
        System.out.println("agree      = " + (Math.abs(sequential - parallel) < 1e-9));
    }
}

How it works

Custom Collector With Combiner comes down to the classes StreamingVariance and Welford and the function main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

What the file exposes as its entry: public static void main(String[] args)

Output lines are prefixed (sequential =, parallel =, agree =), and that keeps each printed line traceable to its step.

Key statements

m2 += other.m2 + delta * delta * count * other.count / n;
return count < 2 ? Double.NaN : m2 / (count - 1);
mean += delta * other.count / n;

Interactive Tools for This Topic

FAQ

What does Custom Collector With Combiner print when run?
Execute the whole file; each printed line is prefixed with a label like `sequential =`, `parallel =`, `agree =`.