Lambda 表达式是用来给 函数式接口 的变量或形参赋值使用的。
本质上,Lambda 表达式是用于实现 函数式接口 的 抽象方法 。
语法:
(形参列表) -> {Lambda体}说明:
(形参列表):就是要赋值的函数式接口的抽象方法的 (形参列表) 。
{Lambda体}:就是实现这个抽象方法的方法体。
->:Lambda操作符。
优化:
当 {Lambda体} 只有一条语句的时候,可以省略 {} 和 {;} 。
当 {Lambda体} 只有一条语句的时候,并且这个语句还是 return 语句的时候,return 也可以省略,但是如果 {;} 没有省略,那么 return 是不可以省略的。
(形参列表) 的类型可以省略。
当 (形参列表) 的形参个数只有一个,那么可以将数据类型和 () 一起省略,但是形参名不能省略。
当 (形参列表) 是空参的时候,() 不能省略。
示例:
package com.github.demo4;
import java.util.
function.IntBinaryOperator;
/** * @author maxiaoke.com * @version 1.0 * */
public class Test {
public static void main(String[] args) {
useIntBinaryOperator(1, 2, (a, b) - >a + b);
}
public static void useIntBinaryOperator(int a, int b, IntBinaryOperator operator) {
int result = operator.applyAsInt(a, b);
System.out.println("result = " + result);
}
}示例:
package com.github.demo5;
import java.util.Set;
import java.util.TreeSet;
/** * @author maxiaoke.com * @version 1.0 * */
public class Test {
public static void main(String[] args) {
Set < Integer > set = new TreeSet < >((a, b) - >a - b);
set.add(10);
set.add(100);
set.add( - 20);
set.add(5);
set.add(1);
System.out.println("set = " + set); // set = [-20, 1, 5, 10, 100] }}示例:
package com.github.demo6;
import java.util.Arrays;
import java.util.List;
import java.util.
function.Consumer;
import java.util.
function.Function;
import java.util.
function.Predicate;
import java.util.
function.Supplier;
/** * @author maxiaoke.com * @version 1.0 * */
public class Test {
public static void main(String[] args) {
userConsumer("abc", s - >System.out.println(s));
useSupplier(() - >String.valueOf(Math.random()));
usePredicate(Arrays.asList("a", "b", "c"), (s) - >s.equals("a"));
useFunction(1, (i) - >String.valueOf(i));
}
public static void userConsumer(String str, Consumer < String > consumer) {
consumer.accept(str);
}
public static void useSupplier(Supplier < String > supplier) {
String s = supplier.get();
System.out.println(s);
}
public static void usePredicate(List < String > list, Predicate < String > predicate) {
for (String s: list) {
if (predicate.test(s)) {
System.out.println(s);
}
}
}
public static void useFunction(Integer num, Function < Integer, String >
function) {
String apply = function.apply(num);
System.out.println(apply);
}
}