更新時間:2022-06-07 09:58:09 來源:動力節點 瀏覽653次
動力節點小編來告訴大家Lambda語法的格式。
//左側: Lambda 表達式的參數列表
//右側: Lambda 表達式中所需執行的功能,即Lambda體
package com.lm;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
//左側: Lambda 表達式的參數列表
//右側: Lambda 表達式中所需執行的功能,即Lambda體
public class TestLambda7 {
// 語法格式一: 無參數無返回值
// ()-> System.out.println("Hello world");
@Test
public void test1() {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello world");
}
};
r.run();
System.out.println("--------------------------");
Runnable r1 = ()-> System.out.println("Hello world");
r1.run();
}
// 語法格式二: 有一個參數,無有返回值
// (x) -> System.out.println(x)
@Test
public void test2() {
Consumer<String> con = (x) -> System.out.println(x);
con.accept("hello world");
}
// 語法格式三: 如果只有有一個參數,小括號可以省略不寫
@Test
public void test3() {
Consumer<String> con = x -> System.out.println(x);
con.accept("hello world");
}
// 語法格式四:有兩個以上參數,有返回值,并且Lammbda 體中有多條語句
//多條語句用大括號
@Test
public void test4() {
Comparator<Integer> com = (x,y) -> {
System.out.println("函數式接口");
return Integer.compare(x,y);
};
Integer result = com.compare(1,2); //比大小
System.out.println(result);
}
// 語法格式五:有兩個以上參數,有返回值,并且Lammbda 體中只有一條語句,
// return和大括號可以省略不寫
// Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
@Test
public void test5() {
Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
Integer result = com.compare(1,2); //比大小
System.out.println(result);
}
// 語法格式六:
// Lammbda 表達式參數列表的數據類型可以省略不寫,JVM編譯器會通過上下文推斷出數據類型,即“類型推斷”
// Comparator<Integer> com = (Integer x,Integer y) -> Integer.compare(x,y);
// Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
// Comparator<Integer> com 這里指定了數據類型
@Test
public void test6() {
Comparator<Integer> com = (Integer x,Integer y) -> Integer.compare(x,y);
Integer result = com.compare(1,2); //比大小
System.out.println(result);
}
//上下文推斷數據類型
@Test
public void test7() {
//由后面推斷數據類型
String[] strs = {"aaa","bbb","ccc"};
//這種情況就沒法推斷數據類型
// String[] strs1;
// strs1 = {"aaa","bbb","ccc"};
//后在<>類型由前面推斷出是String類型
List<String> list = new ArrayList<>();
//這里HashMap不帶數據類型,是由下面的方法參數推斷出來的,這里可以不寫,這是jdk1.8新特性,JDK1.7就會出錯
showMap(new HashMap<>());
}
public void showMap (Map<String,Integer> map){
System.out.println(map);
};
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習