使用lambda表達式可以簡化我們的代碼,但是該表達式的使用有個前提:
實現接口方法,並且該接口中只有一個方法。
語法形式:
- (parameters) -> expression
- (parameters) -> {statements;}
基本用法
1、定義兩個接口類,只有一個方法
package com.company;
/**
* @author
* @date 2020/6/23
*/
public interface MathOperation {
int operation(int a, int b);
}
package com.company;
/**
* @author
* @date 2020/6/23
*/
public interface GreetingService {
void sayMessage(String message);
}
2、labmda表達式語法實習
package com.company;
/**
* @author
* @date 2020/6/23
* 語法形式:
* (parameters) -> expression
* (parameters) -> {statements;}
*/
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
// 類型聲明
MathOperation addition = (int a, int b) -> a + b;
// 類型聲明可以省略
MathOperation subtraction = (a, b) -> a - b;
// 接口方法有返回值,大括號中需要有返回語句
MathOperation multiplication = (int a, int b) -> { return a * b; };
// 沒有大括號,可以省略返回語句
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));
// 不用括號
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
// 用括號
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Runoob");
greetService2.sayMessage("Google");
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
3、使用lambda表達式創建線程
package com.company;
public class Main {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("原來的實現多線程的方法");
}
}).start();
//java8 lambda表達式
new Thread(() ->
System.out.println("這就是java8的創建線程的新方法")
).start();
}
}