lambda表达式是干什么的? 实现接口,快速拿到接口的对象
长什么样? new TestLambda().studentSayHello( ()-> System.out.println("hello") );
或者这样
Student student = TestLambda::hello;
对接口有什么要求? 接口只能有一个待实现的方法
静态或者default方法可以有很多,它们不需要被实现
自定义并使用lambda表达式
interface Student {
void sayHello ( ) ;
}
public class TestLambda {
void studentSayHello ( Student student) {
student. sayHello ( ) ;
}
public static void main ( String[ ] args) {
new TestLambda ( ) . studentSayHello ( ( ) - > System. out. println ( "hello" ) ) ;
}
}
把某个构造方法充当未实现方法体 无论哪个类的构造方法都行
注意返回值与方法参数要一样
interface Student {
void sayHello ( ) ;
}
public class TestLambda {
TestLambda ( ) {
System. out. println ( "hellow" ) ;
}
public static void main ( String[ ] args) {
Student student = TestLambda: : new ;
student. sayHello ( ) ;
}
}
用静态方法充当未实现的方法体 注意方法参数与返回值要一样
interface Student {
void sayHello ( ) ;
}
public class TestLambda {
static void hello ( ) {
System. out. println ( "hellow" ) ;
}
public static void main ( String[ ] args) {
Student student = TestLambda: : hello;
student. sayHello ( ) ;
}
}
使用lambda表达式一些情形
List list = new ArrayList ( ) ;
list. add ( "aa" ) ;
list. add ( "bb" ) ;
list. add ( "cc" ) ;
list. forEach ( ( item) - > System. out. println ( item) ) ;
new Thread ( ( ) - > System. out. println ( "快速实现runnable接口" ) ) . start ( ) ;