1、介紹
我對Lamda表達式的了解是:
就是把我們之前經常接觸的匿名内部類的寫法變成函數式程式設計寫法
如
new Thread(new Runnable() {
@Override
public void run() {
//todo
}
}).start();
變成了
new Thread(()->{ /* todo */ }).start();
省去了類名和實作方法名,僅僅寫 參數+ 内部實作就可以, 看起來會更簡潔。
使用Lambda表達式的前提是: 接口必須是上一篇所講到的函數式接口
2、Lambda表達式文法
- 無參數
( ) -> {
// todo
}
比如:
new Thread(()->{ /* todo */ }).start();
- 單個參數
parm - > {
// todo
}
比如:判斷一個car是否是是自動擋,0 -自動擋 1- 非自動擋
public class Car {
public boolean isAuto(Predicate<Integer> predicate, int type) {
return predicate == null ? false : predicate.test(type);
}
}
boolean auto = car.isAuto(s -> s ==0, 1);
System.out.println("isAuto:" + auto); // false
- 兩個或兩個以上參數
需要用括号括起來
(parm1 , param2)- > {
//todo
}
如
public class Car {
public void printInfomation(BiConsumer<String, String> consumer, String name, String description) {
if (consumer != null) {
consumer.accept(name, description);
}
}
}
//usage
car.printInfomation((name, desc) -> {
System.out.println("Model is " + name + ", description:" + desc);
}, "Volkswagen", "A vehicle brand from Germany");
//output : Model is Volkswagen, description:A vehicle brand from Germany
- 方法實作無傳回值
方法實作部分可以加{}也可以不加
new Thread(() -> System.out.println("hello")).start();
或者
new Thread(() -> {System.out.println("hello");} ).start();
- 方法有傳回值
可以加{} 也可以不加 {}, 但是加了 {}必須要有return 關鍵字
List<Integer> integers = Arrays.asList(11, 2, 8, 0, 5);
Collections.sort(integers, (num1, num2) -> num1 - num2);
System.out.println("integers=" + integers);
//output integers=[0, 2, 5, 8, 11]
但是若果num1-num2加上{}的話,就必須使用return 關鍵字,否則報錯

正确寫法:
List<Integer> integers = Arrays.asList(11, 2, 8, 0, 5);
Collections.sort(integers, (num1, num2) -> {
return num1 - num2;
});
System.out.println("integers=" + integers);