-1

I was trying to convert a lambda expression into method reference, but I failed to do so. can anybody help me with this? The lambda expression takes 2 int parameters adds it and return the result.

public class Addition {

public static void main(String[] args) {
    int a = 10;
    int b = 20;

    A ref = (int c, int d) -> c + d;
    System.out.println(ref.add(a, b));

}

}

Ashish Singh
  • 399
  • 4
  • 11

1 Answers1

4

Based on the signature of the method implemented by your lambda expression, you can replace it with:

A ref = Integer::sum;

Since that sum method accepts two int arguments and returns their int sum:

public static int sum(int a, int b) {
    return a + b;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Can you explain why did you use Integer there? – Ashish Singh Jun 27 '19 at 13:54
  • @AshishSingh in order to use a method reference, you need a method. And Integer class happens to have a `sum` method which matches your lambda expression (i.e. both can implement your function interface). – Eran Jun 27 '19 at 13:56
  • Ow!! So this is something builtin.. :) I wanted If we can modify the code I provided to method reference. But what you posted was great and something new for me. Thanks. :) – Ashish Singh Jun 27 '19 at 13:57
  • @AshishSingh In order to use a method reference with the code you provided, you'd have to create a static method that takes 2 int arguments and returns an int. Then you can reference it with `Addition::methodName`. – Eran Jun 27 '19 at 14:00