Skip to content

Instantly share code, notes, and snippets.

@naffan2014
Last active May 9, 2019 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naffan2014/d279a7b2e36809c2eaaf203d1417e581 to your computer and use it in GitHub Desktop.
Save naffan2014/d279a7b2e36809c2eaaf203d1417e581 to your computer and use it in GitHub Desktop.
增加了w3c的lamda教学代码,确实不错。

函数式接口

需要的条件

  1. 定义一个接口,这个接口必须有且仅有一个方法
  2. 用lamda方法声明这个类
  3. 调用这个方法
interface myTest{
    void testInterface();
}
    
myTest test = () -> System.out.println("test");
test.testInterface();
结果输出 test

w3c上的例子很好,我看完了,全部概念通过代码都讲到了

package lamda;

public class MyLamda {

    public static void main(String args[]){
        MyLamda tester = new MyLamda();

        // 类型声明
        MathOperation addition = (int a, int b) -> a + b;


        // 不用类型声明
        MathOperation subtraction = (a, b) -> a - b;

        // 大括号中的返回语句
        MathOperation multiplication = (int a, int b) -> { return a * b; };

        // 没有大括号及返回语句
        MathOperation division = (int a, int b) -> a / b;

        System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
        System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
        System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
        System.out.println("10 / 5 = " + tester.operate(10, 5, division));

        // 不用括号
        GreetingService greetService1 = message ->
                System.out.println("Hello " + message);

        // 用括号
        GreetingService greetService2 = (message) ->
                System.out.println("Hello " + message);

        greetService1.sayMessage("Runoob");
        greetService2.sayMessage("Google");
    }

    interface MathOperation {
        int operation(int a, int b);
    }

    interface GreetingService {
        void sayMessage(String message);
    }

    private int operate(int a, int b, MathOperation mathOperation){
        return mathOperation.operation(a, b);
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment