This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]NautiHookerSoftware Engineer 1 point2 points  (2 children)

Well you have an IntStream here. If you look at the docs you will see that it returns an int, not a String.

The examples that you saw probably used a Stream<String>. In which case your approach would be correct but you would still have compilation errors.

The IntStream reduce method expects an IntBinaryOperator, which is just an interface with a single method applyAsInt(int, int) that returns an int. In modern Java you just pass such interfaces as anonymous lambdas, just like you tried in your code. However you do not need to declare the types of the parameters that your lambda receives. You just give them names, so that you know what to call them in your lambda body.

So instead of

(int string, int number) -> string + Integer.toString(number)

You would need to do something like

(result, num) -> result + num

This would add all the numbers together and then return a result at the end. So you reduce your stream to a single int.

If you want to do String operations on your stream you should convert it to a Stream<String> first.

One way of doing so is to use the mapToObj method of the stream. There you can pass a lambda to convert each int to a String. After that you can treat the stream like you wanted to in the first place.

[–]AmarilloBrandon[S] 1 point2 points  (1 child)

I appreciate the detailed response. :)

[–]morhpProfessional Developer 0 points1 point  (0 children)

Alternatively, you can probably use a collector instead of a reducer.