Hasnain Ali Bohra Hasnain Ali Bohra - 1 year ago 43
Java Question

why Combiner is not making affect on output?

The following code output is 24 all the time.

public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
list.add("perl");
list.add("c");
list.add("lisp");
list.add("c#");
int s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> 0);
System.out.println(s);
s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x - y);
System.out.println(s);
s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x * y);
System.out.println(s);

}


Question is why combiner is effecting my code.

Answer Source

combiner is only used for parallel streams.

But there might be other problems with your code even if you add parallel. They all violate some rules... Specifically:

Additionally, the combiner function must be compatible with the accumulator function; for all u and t, the following must hold

 combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)

And your combiners violate this, so depending on the number of CPU's you have - you will get different results - which is obviously wrong.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download