lambda表達式的基礎語法 java8引入的新的操作符 “->” 該操作符稱爲箭頭操作符和lambda操作符
箭頭操作符將lambda表達式拆成兩部分:
左側: lambda 表達式的所有參數
右側: lambda 所需執行的功能,即landba體
語法格式一:無參數 無返回值
- ()-> System.out.println(“hello lamdba”);
@Test
public void test1() {
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
};
r1.run();
System.out.println("-----------------");
Runnable r2 = () -> System.out.println("hello lambda");
r2.run();
}
語法格式二:有參數 無返回值
- (x) -> System.out.println(x);
@Test
public void test2() {
Consumer<String> con = (x) -> System.out.println(x);
con.accept("努力努力努力努力努力");
}
語法格式三:若只有一個參數 小括號可以省略不寫
- x -> System.out.println(x);
@Test
public void test3() {
Consumer<String> con1 = x -> System.out.println(x);
con.accept("張藝興---努力努力努力努力努力");
}
語法格式四:有兩個以上的參數,有返回值,並且lamdba有多條語句
- Comparator com = (x,y) -> {
System.out.println(“函數式接口”);
return Integer.compare(x, y);
}
@Test
public void test3() {
Comparator<Integer> com = (x,y) -> {
System.out.println("函數式接口");
return Integer.compare(x, y);
};
語法格式五:當 Lambda 體只有一條語句時,return 與大括號可以省略
- BinaryOperator bo = (x,y) -> x+y;
@Test
public void test3() {
BinaryOperator<Long> bo = (x,y) -> x+y;
}
語法格式六:Lambda參數列表的數據類型可以不寫,因爲jvm編譯器會根據上下文推斷出數據類型 即:”類型推斷“
- Comparator com = (Integer x, Integer y) -> Integer.compare(x, y);
@Test
public void test4() {
Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
}
總結
上聯:左右遇一括號省
下聯:左側推斷類型省
橫批:能省則省
Landba表達式需要“函數式接口”的支持
函數式接口:接口中只有一個抽象方法的接口,稱爲“函數式接口”可以使用註解@FunctionalInterface
修飾,可以檢查是否是函數式接口