简体   繁体   中英

Using an intermediate Operation after a terminal Operation in Java Streams

I was looking through one of the solutions for finding a Normalized mean and I was surprised to come across a solution that uses an intermediate operation (map ) after a terminal Operation( reduce). I tested it myself and it worked.I had read that after a terminal operation is applied the stream ends so why is this solution working at all?.

//Normalized mean
    static double normalizedMean(Stream<Integer> stream) {
        return stream.map(x -> new NM(x,x,x,1))
                .reduce((x, y) -> new NM(x.sum + y.sum,
                        x.max > y.max ? x.max : y.max,
                        x.min < y.min ? x.min : y.min,
                        x.n + 1)
                )
                .map(x -> x.compute())
                .filter(x -> !x.isNaN())
                .orElse(0.0);
    }


class NM {
    final int sum;
    final int max;
    final int min;
    final int n;
    NM(int a, int b, int c, int d) {
        sum = a;
        max = b;
        min = c;
        n = d;
    }
    double compute() {
        return ((double) sum / n - min) / (max - min);
    }
}

This works because the overloaded Stream#reduce method that you're using returns an Optional<T> instead of a Stream<T> .

Unlike a Stream , an Optional has no concept of terminal operations and cannot be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM