美文网首页
java8 lambda

java8 lambda

作者: 追憶逝水年華 | 来源:发表于2017-10-16 15:27 被阅读0次

    java8 lambda

    函数式接口

    • 谓词 Predicate<T> boolean test(T t); T -> boolean
    • 消费者 Consumer<T> void accept(T t); T -> void
    • 映射 Function<T, R> R apply(T t); T -> R
    • 供应者 Supplier<T> T get(); () -> T
    • 一元操作 UnaryOperator<T> extends Function<T, T> T apply(T t); T -> T
    • 二元操作 BinaryOperator<T> extends BiFunction<T,T,T> T apply(T t1, T t2); (T, T) -> T
    • BiPredicate<T,U> boolean test(T t, U u); (T,U) -> boolean
    • BiConsumer<T,U> void accept(T t, U u); (T, U) -> void
    • BiFunction<T,U,R> R apply(T t, U u); (T,U) -> R

    方法引用

    • 指向静态方法的方法引用(例如Integer的parseInt方法,写作Integer::parseInt)。
    • 指向任意类型实例方法的方法引用(例如String的length方法,写作String::length)。
    • 指向现有对象的实例方法的方法引用(假设你有一个局部变量expensiveTransaction用于存放Transaction类型的对象,它支持实例方法getValue,那么你就可以写expensiveTransaction::getValue)。
    lambda 方法引用
    (args) -> ClassName.staticMethod(args) ClassName::staticMethod
    (arg0, rest) -> arg0.instanceMethod(rest) ClassName :: instanceMethod arg0是ClassName类型
    (args) -> expr.instanceMethod(args) expr.instanceMethod

    exp:

    lambda 方法引用
    (args) -> ClassName.staticMethod(args) ClassName::staticMethod
    (arg0, rest) -> arg0.instanceMethod(rest) ClassName :: instanceMethod arg0是ClassName类型
    (args) -> expr.instanceMethod(args) expr.instanceMethod

    构造函数引用

    对于一个现有构造函数,你可以利用它的名称和关键字new来创建它的一个引用:
    ClassName::new。

    • 假设有一个构造函数没有参数。它适合Supplier的签名() -> Apple
      Supplier<Apple> c1 = Apple::new; ==> Supplier<Apple> c1 = () -> new Apple();
    • 如果你的构造函数的签名是Apple(Integer weight),那么它就适合Function接口的签
      名.Function<Integer, Apple> c2 = Apple::new; ==> Function<Integer, Apple> c2 = (weight) -> new Apple(weight)
    • 如果你有一个具有两个参数的构造函数Apple(String color, Integer weight),那么
      它就适合BiFunction接口的签名,BiFunction<String, Integer, Apple> c3 = Apple::new; ==> BiFunction<String, Integer, Apple> c3 = (color, weight) -> new Apple(color, weight);

    相关文章

      网友评论

          本文标题:java8 lambda

          本文链接:https://www.haomeiwen.com/subject/ltokuxtx.html