zoukankan      html  css  js  c++  java
  • 一、Lambda表达式

    一、Lambda是什么?

    Lambda是一个匿名函数,我们可以把Lambda理解为是一段可以传递的代码。可以写出简洁、灵活的代码。作为一种更紧凑的代码风格,使java的语言表达能力得到提升。

    二、Lambda表达式语法

    Lambda表达式在java语言中引入了一个新的语法元素和操作符。这个操作符为"->",该操作符被称为Lambda操作符或箭头操作符,它讲Lambda分为两个部分

      左侧:指定了Lambda表达式所需要的所有参数

      右侧:指定了Lambda体,即Lambda表达式所要执行的功能。

    语法格式一:无参,无返回值,Lambda体只需要一条语句。

    Runnable r1 = () -> System.out.println("Hello Lambda!");

    语法格式二:Lambda需要一个参数

    Consumer<String> con = (x) -> System.out.println(x);

    语法格式三:Lambda只需要一个参数时,参数的小括号可以省略

    Consumer<String> con = x -> System.out.println(x);

    语法格式四:Lambda需要两个参数,并且有返回值

        Comparator<Integer> com = (x, y) -> {
                System.out.println("函数式接口");
                return Integer.compare(x, y);
            };

    语法格式五:当Lambda体只有一条语句时,return与大括号可以省略

    Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

    语法格式六:

    //数据类型可以省略,因为可由编译器推断得出,称为类型推断
            BinaryOperator<Long> operator = (Long x, Long y) -> {
                System.out.println("实现函数接口方法");
                return x + y;
            };

    三、函数式接口

      只包含一个抽象方法的接口,称为函数式接口。可以在任意函数式接口上使用@FunctionalInterface注解,这样做可以检查它是否是一个函数式接口,同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。

    四、自定义函数式接口

    @FunctionalInterface
    public interface MyNumber {
        public double getValue();
    
    }

    函数式接口中使用泛型

    @FunctionalInterface
    public interface MyFunc<T> {
        public T getValue(T t);
    }

    五、作为参数传递Lambda表达式

    public String toUpperString(MyFunc<String> mf, String str) {
            return mf.getValue(str);
        }
    String str = toUpperString((x) -> x.toUpperCase(), "abcdef");
            System.out.println(str);

    作为参数传递Lambda表达式:为了将Lambda表达式作为参数传递,接收Lambda表达式的参数类型必须是与该Lambda表达式兼容的函数式接口类型。

    六、java内置四大核心函数式接口

      1、四大核心接口

      

      ①消费型接口

        //Consumer<T> 消费型接口 :
        @Test
        public void test1(){
            happy(10000, (m) -> System.out.println(m));
        } 
        
        public void happy(double money, Consumer<Double> con){
            con.accept(money);
        }

      ②供给型接口

    //Supplier<T> 供给型接口 :
        @Test
        public void test2(){
            List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
            
            for (Integer num : numList) {
                System.out.println(num);
            }
        }
        
        //需求:产生指定个数的整数,并放入集合中
        public List<Integer> getNumList(int num, Supplier<Integer> sup){
            List<Integer> list = new ArrayList<>();
            
            for (int i = 0; i < num; i++) {
                Integer n = sup.get();
                list.add(n);
            }
            
            return list;
        }

      ③函数型接口

        //Function<T, R> 函数型接口:
        @Test
        public void test3(){
            String newStr = strHandler("			 好好学习天天向上   ", (str) -> str.trim());
            System.out.println(newStr);
            
            String subStr = strHandler("好好学习天天向上", (str) -> str.substring(2, 5));
            System.out.println(subStr);
        }
        
        //需求:用于处理字符串
        public String strHandler(String str, Function<String, String> fun){
            return fun.apply(str);
        }

      ④断言型接口

        //需求:将满足条件的字符串,放入集合中
        public List<String> filterStr(List<String> list, Predicate<String> pre){
            List<String> strList = new ArrayList<>();
            
            for (String str : list) {
                if(pre.test(str)){
                    strList.add(str);
                }
            }
            
            return strList;
        }
        
        //Predicate<T> 断言型接口:
        @Test
        public void test4(){
            List<String> list = Arrays.asList("Hello", "atntjr", "Lambda", "www", "ok");
            List<String> strList = filterStr(list, (s) -> s.length() > 3);
            
            for (String str : strList) {
                System.out.println(str);
            }
        }

      2、其他接口

      

    七、方法引用于构造器引用

      1、方法引用

      当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!(实现抽象方法的参数列表,必须与方法引用方法参数列表保持一致)

      方法引用:使用操作符"::"将方法名和对象或者类的名字分隔开来。如下三种主要使用情况:

      对象::实例方法

      类::静态方法

      类::实例方法

      注意:

        ①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!

        ②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName。

      2、构造器引用:构造器的参数列表,需要与函数式接口中参数列表保持一致!

      类名::new

      3、数组引用

      类型[] ::new

      例子:

      ①对象的引用::实例方法名

    @Test
        public void test2(){
            Employee emp = new Employee(101, "张三", 18, 9999.99);
            
            Supplier<String> sup = () -> emp.getName();
            System.out.println(sup.get());
            
            System.out.println("----------------------------------");
            
            Supplier<String> sup2 = emp::getName;
            System.out.println(sup2.get());
        }

      ②类名::静态方法名

    @Test
        public void test4(){
            Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
            
            System.out.println("-------------------------------------");
            
            Comparator<Integer> com2 = Integer::compare;
        }

      ③类名::实例方法名

    @Test
        public void test5(){
            BiPredicate<String, String> bp = (x, y) -> x.equals(y);
            System.out.println(bp.test("abcde", "abcde"));
            
            System.out.println("-----------------------------------------");
            
            BiPredicate<String, String> bp2 = String::equals;
            System.out.println(bp2.test("abc", "abc"));
            
            System.out.println("-----------------------------------------");
            
            
            Function<Employee, String> fun = (e) -> e.show();
            System.out.println(fun.apply(new Employee()));
            
            System.out.println("-----------------------------------------");
            
            Function<Employee, String> fun2 = Employee::show;
            System.out.println(fun2.apply(new Employee()));
            
        }

      ④构造器引用

        //构造器引用
        @Test
        public void test7(){
            Function<String, Employee> fun = Employee::new;
            
            BiFunction<String, Integer, Employee> fun2 = Employee::new;
        }

       ⑤数组引用

    @Test
        public void test8(){
            Function<Integer, String[]> fun = (args) -> new String[args];
            String[] strs = fun.apply(10);
            System.out.println(strs.length);
            
            System.out.println("--------------------------");
            
            Function<Integer, Employee[]> fun2 = Employee[] :: new;
            Employee[] emps = fun2.apply(20);
            System.out.println(emps.length);
        }

      

  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/zhaobingqing/p/7193671.html
Copyright © 2011-2022 走看看