简介
Lambda表达式是Java 8的一个新特性,允许使用者用更简洁的代码创建一个函数式接口实例。
函数式接口:只有一个抽象方法的接口。
举例1,简化比较器
PriorityQueue< Integer> pq = new PriorityQueue < > ( 10 , new Comparator < Integer> ( ) {
@Override
public int compare ( Integer o1, Integer o2) {
return o2. compareTo ( 01 ) ;
}
} ) ;
PriorityQueue< Integer> pq1 = new PriorityQueue < > ( 10 , ( o1, o2) - > o2. compareTo ( o1) ) ;
举例2,简化创建线程
Thread t1 = new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
System. out. println ( 123 ) ;
}
} ) ;
Thread t2 = new Thread ( ( ) - > System. out. println ( 123 ) ) ;
表达式语法
一.一般写法
( Type1 param1, Type2 param2, . . . , TypeN paramN) - > {
statment1;
statment2;
return statmentM; }
形参列表:允许省略形参类型,如果只有一个参数,可省略圆括号 箭头(->) 代码块:如果只有一条语句可省略花括号和return,但不能一个省略一个不省略,负责会报错。
二. "::"表达式
如果代码块只有一条代码有些情况下可用更简单的::去表达
种类 示例 对应的Lambda表达式 引用类方法 类名::类方法 (a,b,…)->类名.类方法(a,b,…) 应用特定对象的实例方法 特定对象::实例方法 (a,b,…)->特定对象.实例方法(a,b,…) 某类对象的实例方法 类名::实例方法 (a,b,…)->a.实例方法(b,…) 引用构造器 类名::new (a,b,…)->new 类名(a,b,…)
举例
interface Converter {
Integer convert ( String from) ;
}
interface MyTest {
String test ( String a, int b, int c) ;
}
interface YourTest {
Demo2 win ( ) ;
}
public class Demo2 {
public static void main ( String[ ] args) {
Converter c1 = from- > Integer. valueOf ( from) ;
Converter c11 = Integer: : valueOf;
Converter c2 = from- > "abcdef" . indexOf ( from) ;
Converter c22 = "abcdef" : : indexOf;
MyTest m1 = ( a, b, c) - > a. substring ( b, c) ;
MyTest m2 = String: : substring;
YourTest y1 = ( ) - > new Demo2 ( ) ;
YourTest y2 = Demo2: : new ;
}
}
Lambda表达式与匿名内部类的区别与联系
联系:Lambda表达式是匿名内部类的简化
都可以访问局部变量和外部类的成员变量 都可以直接调用从接口中继承的默认方法
区别:
Lambda表达式只能为函数式接口创建实例 Lambda表达式代码块中不允许直接调用定义中的默认方法