Monday, 29 June 2015

Java Lambda Demo

public class LamdaDemo {
   public static void main(String args[]){
      LamdaDemo lamda = new LamdaDemo();

      //type declaration
      BasicMaths add = (int a, int b) -> a + b;

      //no type declaration
      BasicMaths subtract = (a, b) -> a - b;

      //with return statement
      BasicMaths product = (int a, int b) -> { return a * b; };
      
      BasicMaths quotient = (int a, int b) -> a / b;

      System.out.println("1 + 1 = " + lamda.operate(1, 1, add));    
      System.out.println("1 - 1 = " + lamda.operate(1, 1, subtract));
      System.out.println("1 x 1 = " + lamda.operate(1, 1, product));
      System.out.println("1 / 1 = " + lamda.operate(1, 1, quotient));

       
   }   

   interface BasicMaths {
      int execute(int a, int b);
   }  

  
   private int operate(int a, int b, BasicMaths basicMaths){
      return basicMaths.execute(a, b);
   } 
}

No comments:

Post a Comment