Java Stream How to - Create functional interface to calculate on two entities








Question

We would like to know how to create functional interface to calculate on two entities.

Answer

//from  w  w  w.ja v a 2s .  c o  m
public class Main {
  public static void main(String[] args) {
    // Integer's sum
    MyCal<Integer> myOwnCalculatorFI = (a, b) -> (a + b);

    Integer sum = myOwnCalculatorFI.calcIt(5, 5);

    System.out.println("Sum: " + sum);

    // String's sum
    MyCal<String> myOwnCalculatorFI1 = (e, f) -> (e + f);
    System.out.println("Adder: " + myOwnCalculatorFI1.calcIt("a", "b"));

    // Double's power
    MyCal<Double> calculator2 = (a, b) -> (Math.pow(a, b));
    System.out.println("Integer's range: " + calculator2.calcIt(2D, 32D));
  }
}

interface MyCal<T> {

  public T calcIt(T t1, T t2);
}

The code above generates the following result.