Lambda 表達式,自從被Java8引入以來,真的堪稱是最大最重量級的新特性。 Lambda豐富了功能化編程,簡化了程序員的代碼書寫。
語法
parameter -> expression body
what? Are you kidding me?
這么簡單?
是的 就是這么簡單!
我們來看看lambda的一些重要特點:
- 可選的類型聲明:簡單的來說 就是我們在使用lambda表達式的時候,不再需要首先定性變量或者參數(shù)的類型,因為編譯器可以runtime的環(huán)境中自動幫你推斷出變量的類型,臥槽 是不是碉堡了
- 可選的參數(shù)括號: 如果你的參數(shù)只有一個的話,那么你闊以直接省略掉這個括號。但是多個參數(shù)的話,括號還是需要的。
- 可選的方法大括號: 如果你的語句只有一句的話,那么你可以連方法的大括號都不用寫。所以就變成了上面的那種形式。
- 可選的返回值關(guān)鍵詞:簡單來說如果你方法體只有一句話并且?guī)в蟹祷刂?,那么你可以不用再?strong>return了, 連return都給你省略了,因為編譯器會幫你自動的返回這個值
說了這么多,那我們來看看具體的用法吧,光說不練假把式, 代碼見
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
//with type declaration
MathOperation addition = (int a, int b) -> a + b;
//with out type declaration
MathOperation subtraction = (a, b) -> a - b;
//with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> { return a * b; };
//without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
//without parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
//with parenthesis
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Orange");
greetService2.sayMessage("Cat");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
驗證結(jié)果
如果你直接使用IDE的話,直接運行就好,如果你喜歡用命令行的話,
$javac Java8Tester.java
$java Java8Tester
結(jié)果:
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Orange
Hello Cat
Lambda表達式主要還是被用來定義那些只有一個方法的接口,這種情況下,我們可以直接使用Lambda表達式來省略我們的大量方法。它最大的好處就是 消除了繁雜的匿名內(nèi)部類 的寫法,各種大括號,小括號。
我相信有Android開發(fā)經(jīng)驗的人應(yīng)該能了解吧。那種匿名內(nèi)部類給你帶來的恐懼