龙空技术网

Lambda 表达式

爪哇程序猿 93

前言:

当前姐妹们对“lambda的表达式”大体比较着重,同学们都需要学习一些“lambda的表达式”的相关知识。那么小编同时在网上收集了一些有关“lambda的表达式””的相关文章,希望小伙伴们能喜欢,咱们快快来学习一下吧!

小编整理Lambda已经有一段时间了,今天来个Lambda的小总结:

1. 什么是λ表达式

λ表达式本质上是一个匿名方法

public int add(int x, int y) { return x + y; }

转成λ表达式后是这个样子: (int x, int y) -> x + y;

参数类型也可以省略,Java编译器会根据上下文推断出来:

(x, y) -> x + y; //返回两数之和 或者

(x, y) -> { return x + y; } //显式指明返回值

可见λ表达式有三部分组成:参数列表,箭头(->),以及一个表达式或语句块。

2.重要的函数接口 //@FunctionalInterface

/** * 关于函数接口 *1.如果一个接口只有一个抽象方法,那么该接口就是一个函数接口 * 2.如果我们在某个接口上声明FunctionalInterface注解 那么编译器就会按照函数的定义要求该接口 * 3.如果某个接口只有一个抽象方法 但没有声明functionalInterface注解 那么编译器依旧会将该接口看作函数接口 */
  * stream 串行流 单线程  * parallelStream 并行流  *  * map 方法相当于映射  * Function<T,R> t 输入的类型 R 输出的类型

* LAmbda 是一种匿名函数没有声明的方法,没有访问修饰符 返回值声明和名字

* 传递行为,而不仅仅是值

* 提升抽象层次

* API重用


* 一个Lambda表达式可以有多个或者0个参数

* 所有的参数在()内 空括号元素为空

一个函数接收一个函数作为参数 或者返回一个函数的返回值 那么该函数就叫做高阶函数
 //Function俩个function嵌套    /*    * default <V> Function<V, R> compose(Function<? super V, ? extends T> before)  {     *    Objects.requireNonNull(before);     *    return (V v) -> apply(before.apply(v));     * }     * compose先应用参数的apply方法 先执行func2的apply 2*2 作为参数执行func1的apply 2*2*3     */    public int compute(int a, Function<Integer,Integer> func1,  Function<Integer,Integer> func2){        return func1.compose(func2).apply(a); //12    }    /**     * default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {     *     Objects.requireNonNull(after);     *     return (T t) -> after.apply(apply(t));     * }     * andThen 先应用当前对象apply方法 先执行func1的apply 2*3 作为参数执行func1的apply (2*3)*(2*3)     */    public int compute2(int a, Function<Integer,Integer> func1,  Function<Integer,Integer> func2){        return func1.andThen(func2).apply(a); //36    }    //BiFunction    /**     *  BiFunction<T,U,R>接口 函数会接收2个参数得到一个结果 Function接口的一种特化形式     *  R apply(T t,U u);     */    public int compute(int a,int b,BiFunction<Integer,Integer,Integer> func){        return func.apply(a,b);    }    /** * default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) { *    Objects.requireNonNull(after); *    return (T t, U u) -> after.apply(apply(t, u)); * } * System.out.println(test06.compute(1,2,(value1,value2)->value1+value2,value->value*2)); * 1+2=3 把3当成function的输入计算3*2 = 6 */public int compute(int a,int b,BiFunction<Integer,Integer,Integer> func1,Function<Integer,Integer> func2){    return func1.andThen(func2).apply(a,b);}
//Predicatepublic static void main(String[] args) {      Predicate<String> predicate = p->p.length()>5;      predicate.test("hello");      //满足条件返回true or false      System.out.println(predicate.test("hello"));}
//Predicatepublic static void main(String[] args) {      Predicate<String> predicate = p->p.length()>5;      predicate.test("hello");      //满足条件返回true or false      System.out.println(predicate.test("hello"));}

欢迎大家去查看之前关于Lambda的详细讲解!

欢迎大家留言 互相切磋学习!

标签: #lambda的表达式