Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question on reduce function #603

Open
Keefetgy opened this issue Apr 27, 2022 · 4 comments
Open

Question on reduce function #603

Keefetgy opened this issue Apr 27, 2022 · 4 comments

Comments

@Keefetgy
Copy link

Hi! Can i check why this code runs into an error?
List.of("abc","def").stream().reduce(0, (x,y) -> x + y.length())

@weiming21
Copy link

weiming21 commented Apr 27, 2022

Hi I believe you would have to add in a combiner for it to work since the x and y in your code are of two different types.
Therefore you could not use the T reduce(T identity, BinaryOperator accumulator) since it works only for the same types and you should use the U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator combiner) method in the java api.

In your case, you can do List.of("abc","def").stream().reduce(0, (x,y) -> x + y.length(), (x,y) -> x + y) as suggested by the lecture slides

@kaitlyngoh
Copy link

hi idk if this makes sense but youre taking in and returning 2 different types so you need the accumulator to combine it before you can use the (x, y) -> x + y

@calvinseptyanto
Copy link

You need to put the combiner as the third argument, can try "Integer::sum" or (x, y) -> x+y

CMIIW I think it's because the compiler somehow still perceive the output to be "String" per se from ur code, that's why u need to give a combiner to tell the compiler you need to return an integer

@Lu-Yi-Fan
Copy link

You are missing a combiner or alternatively you can use the reduce method which only makes use of an identity and an accumulator, i did something like this. I combine the words and then count the length!

int count(List words) {
return words.stream()
.reduce("", (x, y) -> x + y)
.length();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants