• java8新特性之方法引用和构造器引用


    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestMethod {
    
        /**
         * 一,方法引用:若Lambda体中的内容有方法已经实现了,我们可以使用“方法引用”
         * (可以理解为方法引用是Lambda表达式的另一种表现形式)
         * 主要有三种语法格式:
         * 对象::实例方法名
         *
         * 类::静态方法名
         *
         * 类::实例方法名
         *
         * 二,构造器引用
         * ClassName::new
         * 注意:需要调用的构造器的参数列表与函数式接口中抽象方法的参数列表保持一致!
         *
         * 三,数组引用
         * Type::new;
         *
         */
    
        //对象::实例名
        @Test
        public void test1() {
            PrintStream ps1 = System.out;
            Consumer<String> con = (x) -> ps1.println(x);
    
            PrintStream ps = System.out;
            Consumer<String> con1 = ps::println;
    
            Consumer<String> con2 = System.out::println;
            con2.accept("abcedf");
        }
    
        //类::静态方法名
        @Test
        public void test2() {
            Comparator<Integer> com = (x,y) -> Integer.compare(x,y);
            Comparator<Integer> com1 = Integer::compare;
        }
    
        //类:: 实例方法名
        @Test
        public void test3() {
            BiPredicate<String,String> bp = (x,y) -> x.equals(y);
            BiPredicate<String,String> bp2 = String::equals;
        }
    
        //构造器引用方式
        @Test
        public void test4() {
            Supplier<Employee> sup = () -> new Employee();
    
            //构造器引用方式
            Supplier<Employee> sup2 = Employee::new;
            Employee emp = sup2.get();
            System.out.println(emp);
    
        }
    
        @Test
        public void test5() {
            Function<Integer,Employee> fun = (x) -> new Employee(x);
            //构造器引用方式
            Function<Integer,Employee> fun2 = Employee::new;
            Employee emp = fun2.apply(101);
            System.out.println(emp);
        }
    
        //数组引用
        @Test
        public void test6() {
            Function<Integer,String[]> fun = (x) -> new String[x];
            String[] strs = fun.apply(10);
            System.out.println(strs.length);
    
            Function<Integer,String[]> fun2 = String[]::new;
    
            String[] strs2 = fun.apply(20);
            System.out.println(strs2.length);
    
        }
    
    }
  • 相关阅读:
    Ubuntu安装截图软件shutter
    Ubuntu18.04安装破解版MATLAB2018b
    Ubuntu18.04安装UHD+GNU Radio后找不到USRP B210解决办法
    USRP B210 更改A通道或B通道
    性能测试总结(三)--工具选型篇
    性能测试总结(二)---测试流程篇(转载)
    性能测试总结(一)---基础理论篇(转载)
    selenium 自动化测试面试题及答案
    Appium-测试失败后屏幕截图的
    七 Appium常用方法介绍
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/13424044.html
Copyright © 2020-2023  润新知