Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lambda Expression java

I want to return a – b if a > b and b – a if b > a. How do I do that with a lambda expression? I already tried Calculation calculation = (a, b) -> a – b; and () -> a – b;. I know that this isn’t the desired solution yet but I already get a compilation error when trying this and I don’t know how to fix it. "variable a is already defined in method" or "incompatible types".

interface Calculator {
  public int calculate(int a, int b);
}

class Taschenrechner {
  private int doCalculation(int a, int b, Calculation calculation) {
    return calculation.calculate(a, b);
  }
  
  public int difference(int a, int b) {
    Calculation calculation = 
    return doCalculation(a, b, calculation);
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface Calculator {
  public int calculate(int a, int b);
}

public class Taschenrechner {

  private int doCalculation(int a, int b, Calculator calculation) {
    return calculation.calculate(a, b);
  }
  
  public int difference(int a, int b) {
    return doCalculation(a, b, (x,y) -> x > y ? x - y : y - x);
  }

  public static void main(String...args) {
    System.out.println(new Taschenrechner().difference(7, 10));
  }
}

You can inline the lambda, all it needs is to conform with method signature from the interface

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading