privatestaticvoiddoProcess(int a, Consumer<Integer> consumer){ consumer.accept(a); } publicstaticvoidmain(String[] args){ int a = 10; int b = 20; doProcess(a, (i) -> System.out.println(i + b)); }
lambda 简化了匿名内部类,上面代码中的变量 b 会被隐式的加上 final 修饰符,即 b 不可以改变。
privatevoiddoProcess(int i, Consumer<Integer> consumer){ consumer.accept(i); } publicstaticvoidmain(String[] args){ ThisReferenceExample thisRefEx = new ThisReferenceExample(); thisRefEx.doProcess(10, i -> { System.out.println("Value of i is: " + i); // System.out.println(this); this will not work System.out.println("Can not print this in a static method"); });
thisRefEx.execute(); } // lambda 表达式在静态方法中,无法获取 this 引用 输出: Value of i is: 10 Can not print this in a static method
使用匿名内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicstaticvoidmain(String[] args){ ThisReferenceExample thisRefEx = new ThisReferenceExample(); thisRefEx.doProcess(10, new Consumer<Integer>() { @Override public String toString(){ return"this is point to a anonymous inner class"; } @Override publicvoidaccept(Integer i){ System.out.println("Value of i is: " + i); System.out.println(this); } }); } // lambda 表达式在匿名内部类中, this 指向当前内部类 输出: Value of i is: 10 this is point to a anonymous inner class
使用成员方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicstaticvoidmain(String[] args){ ThisReferenceExample thisRefEx = new ThisReferenceExample(); thisRefEx.execute(); } privatevoidexecute(){ this.doProcess(10, i -> { System.out.println("Value of i is: " + i); System.out.println(this); }); } // lambda 表达式在成员方法中, this 指向当前类 输出: Value of i is: 10 this is point to ThisReferenceExample class
方法引用
lambda 表达式如果是调用类中已定义好的方法,可以简写成 类名::方法名
1 2 3 4 5 6 7 8
privatestaticvoidprintMsg(){ System.out.println("Hello"); } publicstaticvoidmain(String[] args){ // Thread thread = new Thread(()-> printMsg()); Thread thread = new Thread(MethodReferenceExample::printMsg); thread.run(); }
Copyright Declaration: This station is mainly used to sort out incomprehensible knowledge. I have not fully mastered most of the content. Please refer carefully.