Lambda表達(dá)式本質(zhì)上是一種語法糖茧球,它支持函數(shù)式接口谨读,即有且僅有一個抽象方法的接口雏搂,常用@FunctionalInterface標(biāo)簽標(biāo)識椒袍。
Lambda表達(dá)式一般的寫法是:
(參數(shù)) -> {返回值;}
1.抽象接口無參數(shù)無返回值:
@FunctionalInterface
interface test1 {
public void run();
}
test1 t1 = () -> System.out.println("");
2.抽象接口只有一個參數(shù):
@FunctionalInterface
interface test1 {
public void run(String x);
}
test1 t1 = (x) -> System.out.println("");
3.抽象接口只有一個參數(shù)時驼唱,參數(shù)的小括號可以省略:
第二點(diǎn)可以寫成
test1 t1 = x -> System.out.println("");
4.Lambda體只有一條語句時,return與大括號均可省略:
@FunctionalInterface //該接口中只能定義一個方法
interface test {
public String run(String string);
}
static class Person {
public String goWalking(String string) {
return "";
}
}
test t = (x) -> { return new Person().goWalking(x);};
可以寫成:
test t = (x) -> new Person().goWalking(x);
方法引用:
格式:對象(類):: 方法名
注意事項:
1.被引用的方法的參數(shù)列表和函數(shù)式接口中的抽象方法的參數(shù)一致
2.當(dāng)接口的抽象方法沒有返回值驹暑,引用的方法可以有返回值也可以沒有返回值
3.接口中的抽象方法有返回值玫恳,引用的方法必須有相同類型的返回值
方法引用:其實(shí)就是用一個接口的子類對象去接受方法引用返回的對象,此時只需要保證接口方法的參數(shù)和返回值必須和調(diào)用方法的返回值和參數(shù)一致优俘。
@FunctionalInterface //該接口中只能定義一個方法
interface test {
public String run(String string);
}
//定義一個對象
class Person {
//引用方法的參數(shù)和返回值和抽象方法一致
public String goWalking(String string) {
return "";
}
}
Lambda寫法:
Person person = new Person();
//獲取接口的子類對象
test t2 = person::goWalking;
System.out.println(t2.run("對象"));
轉(zhuǎn)變?yōu)檎懛ǎ?/p>
Person person = new Person();
test t2 = new test() {
@Override
public String run(String string) {
return person.goWalking(string);
}
};
System.out.println(t2.run("對象"));