Pratyush Kumar Das
Pratyush Kumar Das

Reputation: 13

Reduce function with 2 parameters and 3 parameters

There are three overloaded reduce methods. I m stuck with the one accepting two parameters and three parameters. In both the cases, the second parameter accepts accumulator while one of them only compiles.

CODE 1

String str = "hello";
str = str.chars().mapToObj(c -> (char) c).reduce("", (s, c) -> c + s, (s, c) -> c + s);

CODE 2

String str = "hello";
str = str.chars().mapToObj(c -> (char) c).reduce("", (s, c) -> c + s);

CODE 2 does not even compile whereas the CODE 1 works fine to reverse a string. Both the reduce method accepts accumulator as the second argument then why does this difference in behavior. Why adding a combiner resolves the compilation issue? Also please note that even if the combiner is added it is never used while reversing the string. How does it impact?

Upvotes: 0

Views: 22

Answers (0)

Related Questions