I am learning Java 8 and I am trying to use lambdas and generics together and I wrote this small example
import java.util.function.*;
public class LambdaTest<T> {
public T calculate(T x, T y, BiFunction<T, T, T> func) {
return func.apply(x, y);
}
public static void main(String args[]) {
LambdaTest<Integer> l = new LambdaTest<Integer>();
System.out.println("" + l.calculate(10, 10, (x, y) -> x + y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x * y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x / y));
System.out.println("" + l.calculate(10, 10, (x, y) -> x - y));
LambdaTest<Double> l2 = new LambdaTest<Double>();
System.out.println("" + l2.calculate(10.0, 10.0, (x, y) -> x + y));
}
}
Few questions I have are
My lambdas are being defined twice (x, y) -> x + y. is it possible to define these only once.
It seems that everytime this code is run, it will box 10 to Integer and then run the code. is it possible that I can define this for int rather than Integer. I tried doing new LambdaTest<int> but it did not work.
BiFunction<Integer, Integer, Integer>, whereas the other is of type BiFunction<Double, Double, Double>. They're thus not compatible with each other.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With