Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambdas and Generics

Tags:

java

java-8

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

  1. My lambdas are being defined twice (x, y) -> x + y. is it possible to define these only once.

  2. 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.

like image 680
Knows Not Much Avatar asked Nov 17 '25 05:11

Knows Not Much


1 Answers

  1. No. One is of type BiFunction<Integer, Integer, Integer>, whereas the other is of type BiFunction<Double, Double, Double>. They're thus not compatible with each other.
  2. To avoid the unboxing and the boxing, you would have to use DoubleBinaryOperator and IntBinaryOperator, which use primitive types. But then you would need two different interfaces.
like image 55
JB Nizet Avatar answered Nov 18 '25 18:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!