Thursday, September 11, 2014

Note on Lambda Expression

Ways to understand it:

1. A lambda expression is a way to have a method implementation:
(a,b)->a+b;
(a,b) is correspondingly to method's parameters. if there's only one parameter, parenthesis can be ignored.
->: arrow  token has to be there.
a+b: this is the implementation of  functional method.
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)); 
 } 
}

2. Lambda expressions enable you to treat functionality as method argument, or code as data.
you use it to replace the anonymous function.

It let you express instances of single-method anonymous classes more compactly.

If you have a situation of passing an anonymous class as a method's parameter, you have good chance to use Lambda expression.

interface CheckPerson {
    boolean test(Person p);
}

public static void printPersons(
    List roster, CheckPerson tester) {
    for (Person p : roster) {
        if (tester.test(p)) {
            p.printPerson();
        }
    }
}

In the invocation, you use anonymous class

printPersons(
    roster,
    new CheckPerson() {
        public boolean test(Person p) {
            return p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25;
        }
    }
);

The CheckPerson interface is a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.) Because a functional interface contains only one abstract method, you can omit the name of that method when you implement it. To do this, instead of using an anonymous class expression, you use a lambda expression, which is highlighted in the following method invocation:


printPersons(
 roster,
 (Person p) -> p.getGender() == Person.Sex.MALE
 && p.getAge() >= 18
 && p.getAge() <= 25
);

No comments: