JDK8新特性之【lambda表达式】

276 阅读1分钟

lambda表达式

定义:lambda表达式(也称为闭包),是jdk8发布之后最受期待的java语法提升。lambda允许把一个函数作为参数传递给方法,或者把代码看成数据。 lambda用于简化接口式的匿名内部类。

语法: (参数1,参数2...)-> {...}

1、替代匿名内部类

public void oldRunnable(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("The old runable now is using!");
            }
        }).start();
    }

public void runnable(){
    new Thread(() -> System.out.println("It's a lambda function!")).start();
}

2、Lamda语法有三种形式:

  • (参数) ->单行语句;
  • (参数) ->{多行语句};
  • (参数) ->表达式;

(参数) ->单行语句:

interface MyInterface{

    void lMethod(String str);
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod("Hello World!");//设置参数内容
    }

    public static void main(String[] args) {
        //首先在()中定义此表达式里面需要接收变量s,后面的单行语句中就可以使用该变量了
        test((s)->System.out.println(s));
    }
}

(参数) ->{多行语句}:

interface MyInterface{

    void lMethod(String str);
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod("Hello World!");//设置参数内容
    }

    public static void main(String[] args) {
        //首先在()中定义此表达式里面需要接收变量s,后面的多行语句中就可以使用该变量了。注意:多行语句别少“;”号
        test((s)->{
            s = s+s;
            System.out.println(s);
        });
    }
}

(参数) ->表达式

interface MyInterface{

    int lMethod(int a,int b);
}
public class Main {

    public static void test(MyInterface myInterface){
        int result = myInterface.lMethod(1,2);//设置参数内容,接收返回参数
        System.out.println(result);
    }
    public static void main(String[] args) {

        test((x,y)-> x*y );//调用方法
        //相当于
        //test((x,y)-> {return  x*y;});
    }
}

这样,Lamda表达式就看起来很简单了,有不有!

总结:利用Lamda表达式是为了避免匿名内部类定义过多无用的操作。