Lambda 是一个匿名函数,我们可以把Lambda 表达式理解为是一段可以传递的代码(将代码 像数据一样进行传递)。可以写出更简洁、更 灵活的代码。作为一种更紧凑的代码风格,使 Java的语言表达能力得到了提升。
Lambda 表达式在Java 语言中引入了一个新的语法元 素和操作符。这个操作符为 “->” , 该操作符被称 为 Lambda 操作符或剪头操作符。它将 Lambda 分为 两个部分: 左侧:指定了 Lambda 表达式需要的所有参数 右侧:指定了 Lambda 体,即 Lambda 表达式要执行 的功能。
() -> System.out.println("Hello Lambda!");
(x) -> System.out.println(x)
x -> System.out.println(x)
Comparator<Integer> com = (x, y) -> {
System.out.println("函数式接口");
return Integer.compare(x, y);
};
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
因为JVM编译器通过上下文推断出,数据类型,即“类型推断”
(Integer x, Integer y) -> Integer.compare(x, y);
@FunctionalInterface
注解, 这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包 含一条声明,说明这个接口是一个函数式接口。@FunctionalInterface
public interface Number {
public Integer getValue(Integer num);
}
函数式接口中使用泛型:
@FunctionalInterface
public interface MyNumber{
public T getValue(T t);
}
public String toUpperString(MyFunc<String> mf,String str){
return mf.getValue(str);
}
作为参数传递Lambda表达式:
String newStr=toUpperString(
(str)->str.toUpperCase(),"abcdef");
System.out.pringln(newStr);
作为参数传递 Lambda 表达式:为了将 Lambda 表达式作为参数传递,接收Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口的类型。
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
Consumer<T> 消费型接口 | T | void | 对类型为T的对象应用操 作,包含方法: void accept(T t) |
Supplier<T> 供给型接口 | 无 | T | 返回类型为T的对象,包 含方法:T get(); |
Function<T, R> 函数型接口 | T | R | 对类型为T的对象应用操 作,并返回结果。结果 是R类型的对象。包含方 法:R apply(T t); |
Predicate<T> 断定型接口 | T | boolean | 确定类型为T的对象是否 满足某约束,并返回 boolean 值。包含方法 boolean test(T t); |
函数式接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
BiFunction<T, U, R> | T,U | R | 对类型为 T, U 参数应用 操作,返回 R 类型的结 果。包含方法为R apply(T t, U u); |
UnaryOperator<T> (Function子接口) | T | T | 对类型为T的对象进行一 元运算,并返回T类型的 结果。包含方法为 T apply(T t); |
BinaryOperator<T> (BiFunction 子接口) | T,T | T | 对类型为T的对象进行二 元运算,并返回T类型的 结果。包含方法为 T apply(T t1, T t2); |
BiConsumer<T, U> | T,U | void | 对类型为T, U 参数应用 操作。包含方法为 void accept(T t, U u) |
ToIntFunction<T> ToLongFunction<T> ToDoubleFunction<T> | T | int long double | 分 别 计 算 int 、 long 、 double、值的函数 |
IntFunction<R> LongFunction<R> DoubleFunction<R> | int long double | R | 参数分别为int、long、 double 类型的函数 |