Java8中的Lambda表达式

版权声明:随意转载,请勿商用。转载请注明出处,谢谢。 https://blog.csdn.net/xinhongyang/article/details/86617195

Lambda表达式

在哪里使用Lambda表达式

可以在函数式接口上使用Lambda表达式

函数式接口:只定义一个抽象方法的接口。(默认方法无所谓)@FunctionalInterface
函数描述符

函数式接口的抽象方法的签名就是Lambda表达式的签名,这种抽象方法叫做函数描述符。

Lambda表达式的语法

参数列表 -> Lambda主体

Lambda主体有如下两种方式:

  • 一个对象
(String s) -> s.length()
(Apple a) -> a.getWeight() > 150
  • 代码块
(int x, int y) -> {
	System.out.println("Result:");
	System.out.println(x+y);
}

内置的函数式接口

函数式接口 原始类型特化 接口
Predicate<T> IntPredicate,LongPredicate, DoublePredicate boolean test(T t)
Consumer<T> IntConsumer,LongConsumer, DoubleConsumer void accept(T t)
Function<T,R> IntFunction<R>, IntToDoubleFunction, IntToLongFunction R apply(T t)
LongFunction<R>, LongToDoubleFunction, LongToIntFunction
DoubleFunction<R>
ToIntFunction<T>, ToDoubleFunction<T>, ToLongFunction<T>
Supplier<T> BooleanSupplier,IntSupplier, LongSupplier,DoubleSupplier T get()
UnaryOperator<T> IntUnaryOperator,LongUnaryOperator,DoubleUnaryOperator T apply(T t)
BiFunction<T,U,R> ToIntBiFunction<T,U>,ToLongBiFunction<T,U>,ToDoubleBiFunction<T,U> R apply(T t , U u)
BinaryOperator<T> IntBinaryOperator,LongBinaryOperator,DoubleBinaryOperator T apply(T t1, T t2);
BiPredicate<L,R> boolean test(T t, U u)
BiConsumer<T,U> ObjIntConsumer<T>,ObjLongConsumer<T>,ObjDoubleConsumer<T> void accept(T t, U u)

Lambda的类型检查,推断和限制

类型检查

Lambda的类型检查很简单,如下图例子所示:
图片

类型推断

Java编译器会从上下文(目标类型)推断出用什么函数式接口来配合Lambda表达式,这意味着它也可以推断出适合Lamdba的签名,因为函数描述符可以通过目标类型来得到。

限制

局部变量必须显式声明为final,或者事实上是final。因为Java在匿名内部类访问参数其实访问的是这个参数的副本。

方法引用

指向静态方法的方法引用(例如Integer的parseInt方法,可以写作Integer::parseInt
指向任意类型实例方法的方法引用(例如String的length方法,写作String::length
指向现有对象的实例方法的方法引用(假设有一个局部变量expensiveTransaction用于存放Transaction类型的对象,它支持实例方法getValue,那么可以写作expensiveTransaction::getValue

构造函数引用

无参构造函数引用:ClassName::New 使用的是Supplier
一个参数的构造函数引用:适合Function接口的签名
两个参数的构造函数引用:适合BiFunction接口的签名
两个以上参数的构造函数引用:需要自定义一个函数式接口

复合Lambda表达式

  • 比较器复合
    • 逆序
    inventory.sort(comparing(Apple::getWeight).reversed());
    
    • 比较器链
    inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));
    
  • 谓词复合‘
    Predicate<Apple> notRedApple = redApple.negate();
    
    Predicate<Apple> redAndHeavyApple = redApple.and(a -> a.getWeight() > 150);
    
    Predicate<Apple> redAndHeavyAppleOrGreen =redApple.or(a -> "green".equals(a.getColor()));
    
  • 函数复合
    • andThen
    f.andThen(g); //g(f(x))
    
    • compose
    f.compose(g); //f(g(x))
    

猜你喜欢

转载自blog.csdn.net/xinhongyang/article/details/86617195
今日推荐