zoukankan      html  css  js  c++  java
  • Lambda表达式的语法与如何使用Lambda表达式

    Lambda表达式是对象,是一个函数式接口的实例

    如何来写Lambda表达式?

    • 看参数
    • 看返回值   


    代码实例1:

    package day2;
    
    import jdk.nashorn.internal.codegen.CompilerConstants;
    
    import java.lang.reflect.Type;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.function.Function;
    import java.util.function.UnaryOperator;
    
    /**
     * @auther hhh
     * @date 2018/12/27 21:32
     * @description
     */
    public class LambdaExpress {
        /**
         * Lambda 表达式语法:
         *      args -> expr (左边是参数,右边是表达式)
         *      或者 (Object...args )->{函数式接口抽象方法的实现逻辑}
         *      ()里面参数的个数,根据函数式接口里面的抽象方法的参数个数来决定
         *      只有一个参数的时候,()可以省略
         *      当expr逻辑非常简单的时候,{}和return都可以省略
         */
        /**
         * 表达式示例:
         *      () -> {} //无参,无返回值
         *      () -> {System.out.println(1);} //无参,无返回值
         *      () -> System.out.println(1)//无参,无返回值,上面的简写,将{}省略
         *      () -> {return 100;} //无参有返回值
         *      () -> return 100; // 无参又返回值
         *      () -> null ; //无参又返回值,返回null
         *      (int x) -> {return x+1;} //单参,有返回值
         *      (int x) -> return x+1;
         *      (x) -> x+1  //单参,又返回值(不指定参数类型,多个参数必须用括号)
         *      x -> x+1 //单参数,有返回值(不指定参数类型)
         */
        /**
         * 注意事项:(以下实现是错误的)
         * (x,int y) -> x+y (不能部分省略)
         * (x,final y) -> x+y (参数不能使用final修饰符)
         * Object o = () -> "hello" (不能将Lambda表达式赋值给一个非函数式接口)
         * Object obj = (Supplier<?>)() ->"hello" (不需要也不允许使用throws语句来声明他可能会抛出的异常)
         */
        public static void main(String[] args) throws Exception {
            //语法:LambdaParameters -> LambdaBody (返回值必须是函数式接口)
            Runnable r1 = () -> System.out.println("r1");
            Runnable r5 = () -> {
                System.out.println("r5");
            };
            //不是用lambda表达式
            Runnable r4 = new Runnable() {
                @Override
                public void run() {
                    System.out.println("r4");
                }
            };
            r1.run();
            r4.run();
            Runnable r2 = null;
            Runnable r3 = () -> {
            };
    
            Callable<String> call1 = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return "不适用lambda";
                }
            };
            Callable<String> call2 = () -> {
                return "使用lambda;";
            };
            Callable<String> call3 = () -> "使用lambda简化,不需要人return与{}";
            //call2 中的call方法是在函数式接口中实现的
            System.out.println(call1.call() + "===" + call2.call() + "===" + call3.call());
    
            UserMapper userMapper = new UserMapper() {
                @Override
                public void insert(User user) {
                    System.out.println(" insert user");
                }
            };
            UserMapper u2 = (User user) -> System.out.println("use lambda insert user");
            userMapper.insert(new User());
            u2.insert(new User());
            OrderMapper orderMapper = new OrderMapper() {
                @Override
                public int insert(Order order) {
                    return 1;
                }
            };
            OrderMapper o1 = (Order order) -> 1;
            OrderMapper o2 = (order) -> {
                return 1;
            };
            OrderMapper o3 = (Order order) -> {
                return 1;
            };
            //省略参数类型
            OrderMapper o4 = (order) -> 1;
    
            //Function<T,R> 代表一个输入一个输出,一般输入输出是不同类型
            Function<Integer, Integer> f1 = (a) -> {
                int sum = 0;
                for (int i = 1; i <= a; i++) {
                    sum += i;
                }
                return sum;
            };
            //UnaryOperator<T> 继承自Function<T,R>一般输入输出是同种类型,因为输入输出是同种类型,所以之传了一个参数,省略输出类型
            UnaryOperator<Integer> unaryOperator = (a) -> {
                int sum = 0;
                for (int i = 0; i < a; i++) {
                    sum += a;
                }
                return sum;
            };
            System.out.println("sum = " + f1.apply(10));
            System.out.println("sum = " + unaryOperator.apply(10));
            //尝试使用for循环进行遍历
            List<Integer> list = new ArrayList<>();
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
            UnaryOperator<List<Integer>> unaryOperator2 = (l) -> {
                for (Integer i : list) {
                    list.set(i - 1, i + 1);
                }
                return list;
            };
            System.out.println(unaryOperator2.apply(list));
        }
    }
    
    
    interface UserMapper {
        void insert(User user);
    }
    
    class User {
    }
    
    interface OrderMapper {
        int insert(Order order);
    }
    
    class Order {
    }

    代码实例2:

    package day2;
    
    import javax.sound.midi.Soundbank;
    
    /**
     * @auther hhh
     * @date 2018/12/27 22:32
     * @description
     */
    public class LambdaExpre2 {
        static int get() {
            System.out.println(1);
            return 1;
        }
    
        static void set() {
        }
    
        static String find() {
            return "";
        }
    
        public static void main(String[] args) throws Exception {
            /**
             *  方法的返回值不是一定会返回,具体是有函数式接口的抽象方法决定的
             *  实现的函数式接口没有返回值,调用的方法的值就不会被返回
             *  Runnable 中方法的实现为  public abstract void run(); 没有返回值
             *  函数式接口只管执行方法,不管没有有返回值
             */
            //Runnable 调用自定义的方法不会报错,但是Runnable方法为什么不报错呢?
            Runnable r1 = () -> get();
            Runnable r2 = () -> set();
    //        Runnable r3 = () -> 100; 不行,因为在Runnable实现的抽象方法中没有返回值,强制返回报错
    
            r1.run();//无输出,说明值没有被返回
    
            //Fun方法在调用set()的时候会报错,是因为Fun中定义的get()方法需要有返回值,而set()方法没有返回值
            Fun f1 = () -> get();
            System.out.println(f1.get());
            Fun f2 = () -> 100;
            Fun f3 = () -> 1 > 5 ? 1 : -1;
            Fun f4 = () -> true ? 1 : -1;
    //        Fun f2 = () -> set();
    //        Fun f3 = () -> find();返回值类型必须一致
        }
    }
    
    interface Fun {
        int get();
    }
    package day2;
    
    import javax.sound.midi.Soundbank;
    
    /**
     * @auther hhh
     * @date 2018/12/27 22:32
     * @description
     */
    public class LambdaExpre2 {
        static int get() {
            System.out.println(1);
            return 1;
        }
    
        static void set() {
        }
    
        static String find() {
            return "";
        }
    
        public static void main(String[] args) throws Exception {
            /**
             *  方法的返回值不是一定会返回,具体是有函数式接口的抽象方法决定的
             *  实现的函数式接口没有返回值,调用的方法的值就不会被返回
             *  Runnable 中方法的实现为  public abstract void run(); 没有返回值
             *  函数式接口只管执行方法,不管没有有返回值
             */
            //Runnable 调用自定义的方法不会报错,但是Runnable方法为什么不报错呢?
            Runnable r1 = () -> get();
            Runnable r2 = () -> set();
    //        Runnable r3 = () -> 100; 不行,因为在Runnable实现的抽象方法中没有返回值,强制返回报错
    
            r1.run();//无输出,说明值没有被返回
    
            //Fun方法在调用set()的时候会报错,是因为Fun中定义的get()方法需要有返回值,而set()方法没有返回值
            Fun f1 = () -> get();
            System.out.println(f1.get());
            Fun f2 = () -> 100;
            Fun f3 = () -> 1 > 5 ? 1 : -1;
            Fun f4 = () -> true ? 1 : -1;
    //        Fun f2 = () -> set();
    //        Fun f3 = () -> find();返回值类型必须一致
        }
    }
    
    interface Fun {
        int get();
    }

    代码实例3:

    package day2;
    
    import java.util.function.BiFunction;
    import java.util.function.Function;
    
    /**
     * @auther hhh
     * @date 2018/12/27 22:50
     * @description
     */
    public class BiFuncationTest {
        public static void main(String[] args) {
            //写任何函数式接口(Lambda)先把格式写好,重点是方法参数与返回值
            //BiFunction<T, U, R> b = (参数,因为有两个输入参数,()一定不能省略)->{执行方法,若方法直接返回课省略{}};
            //BiFunction 代表两个输入一个输出
            BiFunction<String, String, Integer> biFunction = (a, b) -> a.length() + b.length();
            System.out.println(biFunction.apply("sadfasdf", "fasdfsdaf"));
            BiFunction<Integer, Integer, String> biFunction2 = (a, b) -> {
                //编写具体代码逻辑
                return "";
            };
            //输入String,输出Integer
            Function<String, Integer> function = a -> a.length();
        }
    }
    package day2;
    
    import java.util.function.BiFunction;
    import java.util.function.Function;
    
    /**
     * @auther hhh
     * @date 2018/12/27 22:50
     * @description
     */
    public class BiFuncationTest {
        public static void main(String[] args) {
            //写任何函数式接口(Lambda)先把格式写好,重点是方法参数与返回值
            //BiFunction<T, U, R> b = (参数,因为有两个输入参数,()一定不能省略)->{执行方法,若方法直接返回课省略{}};
            //BiFunction 代表两个输入一个输出
            BiFunction<String, String, Integer> biFunction = (a, b) -> a.length() + b.length();
            System.out.println(biFunction.apply("sadfasdf", "fasdfsdaf"));
            BiFunction<Integer, Integer, String> biFunction2 = (a, b) -> {
                //编写具体代码逻辑
                return "";
            };
            //输入String,输出Integer
            Function<String, Integer> function = a -> a.length();
        }
    }
  • 相关阅读:
    BAPI_TRANSACTION_COMMIT的使用方法(转)
    Win7 64bit系统下未能加载文件或程序集“System.Data.SQLite”的解决办法
    在Windows XP环境中配置OPC服务器时的设置方式
    关于异常“The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine”的处理
    MSChart使用做折线图饼图(转)
    C#如何导入内文至SAP(转)
    经典Sql大全转
    工程师突击:SAP ABAP实用程序开发攻略(转)
    如何使用ExtJS Design中生成的代码
    ExtJS 4 学习(1)环境配置及注意点
  • 原文地址:https://www.cnblogs.com/huanghuanghui/p/10188050.html
Copyright © 2011-2022 走看看