Reputation:
Trying to test Java8 lambda, but the type is confusing:
import java.util.function.ToIntBiFunction;
import java.util.stream.IntStream;
public class Test {
public static void main(String... args) {
int sum1 = 0;
for (int n = 0; n < 10; n++) {
sum1 += n;
}
ToIntBiFunction<Integer, Integer> add = (a, b) -> a + b;
int sum2 = IntStream.range(0, 10)
.reduce(0, add); //error here
System.out.println(""+sum1);
System.out.println(""+sum2);
}
}
Test.java:15: error: incompatible types: ToIntBiFunction cannot be converted to IntBinaryOperator .reduce(0, add);
What is the most generic way to define the function
(a,b) -> a+b
Thanks.
Upvotes: 0
Views: 380
Reputation: 533680
The most generic way is as a lambda, once you assign it to a variable, or cast it to a type it become a specific type.
Try the type the reduce() expects
IntBinaryOperator add = (a,b) -> a+b
or use the built in one.
int sum2 = IntStream.range(0, 10)
.reduce(0, Integer::sum);
Upvotes: 3
Reputation: 62864
Obviously, you need an IntBinaryOperator
for the .reduce()
, instead of ToIntBiFunction
.
IntBinaryOperator add = (a, b) -> a + b;
int sum2 = IntStream.range(0, 10)
.reduce(0, add);
Upvotes: 0