云台大树  

lambda表达式是从匿名类演变来的,主要就是为了简化代码的编写。 lambda表达式只适用于functional interface,即只有一个default方法的接口

lambda表达式可以访问其所在的块的本地变量,但是它不具备类型遮蔽功能。在表达式内部声明的变量,会被编译器解释成所在块内声明的变量

同样的,类似本地类,lambda表达式能否访问的块内本地变量必须是final或者effectively final,否则会有编译器错误

class Test {
    public String words = "ooxx";
    interface HelloWorld {
        public void sayHi();
    }

    public void sayHello() {
        String words = "nihao";
        /*
         * 不适用匿名类的方式
         * HelloWorld chineseSay = new HelloWorld() {
         * public void sayHi() {
         * System.out.println("你好");
         * }
         * };
         * chineseSay.sayHi();
         */

        HelloWorld chineseSay = () -> {
			/* 在表达式内声明变量会导致编译错误 */
	        // String words1 = "xxx";
            System.out.println(words);
            System.out.println(Test.this.words);
        };
        chineseSay.sayHi();
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.sayHello();
    }
}

方法引用

如果lambda表达式要做的功能,已经有一个现成的方法可以提供,那么就通过方法引用来在表达式内使用这个方法

kind syntax
引用静态方法 ContainingClass::staticMethodName
引用具体类的实例方法 containingClass::instanceMethodName
引用抽象类或具体类型的实例方法 ContainingType::methodName
引用构造函数 ClassName::new
import java.util.function.BiFunction;

public class MethodReference {
    public static void main(String[] args) {
        // calling the method mergeThings with a lambda expression
        System.out.println(MethodReference.mergeThings("hello", "world", (a, b) -> a + b));

        // reference to a static method
        System.out.println(MethodReference.mergeThings("hello", "world", MethodReference::appendStrings));
        // reference to an instance method of a particular object
        MethodReference myApp = new MethodReference();
        System.out.println(MethodReference.mergeThings("hello", "world", myApp::appendString2));

        // reference to an instance method of an arbitrary object of a particular type
        System.out.println(MethodReference.mergeThings("hello", "world", String::concat));
    }

    public static <T> T mergeThings(T a, T b, BiFunction<T, T, T> merger) {
        return merger.apply(a, b);
    }

    public static String appendStrings(String a, String b) {
        return a + b;
    }

    public String appendString2(String a, String b) {
        return a + b;
    }

}
posted on 2022-05-31 21:49  云台大树  阅读(37)  评论(0编辑  收藏  举报