Monday, June 26, 2017

Lambda Expression

public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#syntax



package calculator;

public class Calculator {
  
    interface IntegerMath {
        int operation(int a, int b, int c); 
    }
  
    public int operateBinary(IntegerMath op, int x, int y, int z) {
        //return op.operation(a, b);
        return op.operation(x, y, z);
    }

    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        
        IntegerMath addition = (a, b, c) -> a + b + c;
        IntegerMath subtraction = (a, b, c) -> a - b - c;
        
        System.out.println("40 + 2 = " +
            myApp.operateBinary(addition, 40, 20, 10));
        
        System.out.println("20 - 10 = " +
            myApp.operateBinary(subtraction, 20, 10, 5));    
    }
}



No comments:

Post a Comment