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