Java8學習筆記系列:
一、什麼是Lambda表達式
Lambda是Java8的一個語法糖,它其實是匿名函數,通過約定好怎麼傳入參數,怎麼返回參數,由編譯器負責參數類型的猜測並執行結果。
二、Lambda表達式的基本語法
/**
* Lambda表達式的基本語法
*/
@Test
public void example1(){
//語法格式
//(parameters) -> expression
//(parameters) -> { statements; }
//即"->"操作符將Lambda表達式分爲兩個部分:左側爲參數列表,右側爲Lambda體。
//每一個Lambda表達的返回值都是一個函數式編程的接口
}
三、Lambda表達式的使用示例
/**
* 無參數,無返回
*/
@Test
public void example2(){
Runnable hello_lambda1 = () -> System.out.println("Hello Lambda");
hello_lambda1.run();
//或
Runnable hello_lambda2 = () -> {
System.out.println("Hello Lambda");
};
hello_lambda2.run();
}
/**
* 無參數,有返回
*/
@Test
public void example3(){
Supplier<Integer> supplier1 = () -> 10;
System.out.println(supplier1.get());
//或
Supplier supplier2 = () -> {
return 10;
};
System.out.println(supplier2.get());
}
/**
* 有一個參數,無返回
*/
@Test
public void example4(){
Consumer<String> consumer1 = x -> System.out.println(x);
consumer1.accept("Hello Lambda");
//或
Consumer<String> consumer2 = (x) -> System.out.println(x);
consumer2.accept("Hello Lambda");
//或
Consumer<String> consumer3 = x -> {
System.out.println(x);
};
consumer3.accept("Hello Lambda");
}
/**
* 有一個參數,有返回值
*/
@Test
public void example5(){
IntFunction<Integer> intFunction1 = x -> x + 10;
System.out.println(intFunction1.apply(10));
//或
IntFunction<Integer> intFunction2 = (x) -> {
return x + 10;
};
System.out.println(intFunction2.apply(10));
}
/**
* 有多個參數,無返回值
*/
@Test
public void example7(){
ObjIntConsumer<Integer> objIntConsumer = (x,y) -> {
System.out.println(x + y);
};
objIntConsumer.accept(10,20);
//或
BiConsumer<Integer,Integer> biConsumer = (Integer x, Integer y) -> {
System.out.println(x + y);
};
biConsumer.accept(10,20);
}
/**
* 有多個參數,有返回值
*/
@Test
public void example6(){
IntBinaryOperator intBinaryOperator = (x,y) -> {
return x > y ? x : y;
};
System.out.println(intBinaryOperator.applyAsInt(10,20));
//或
BinaryOperator<Integer> binaryOperator = (Integer x, Integer y) -> {
return x > y ? x : y;
};
System.out.println(binaryOperator.apply(10,20));
}
參考: