方法引用,构造器引用,数组引用

@Test
    public void test1(){
        //1.对象实例(new出来的)::实例方法名 
        PrintStream ps=System.out;
        ps.print("hello");
        //Lambda表达式   依赖于函数式接口
        Consumer<String> con=(str) -> ps.println(str);
        con.accept("好久不见");
        //方法引用
        //1.对象实例::方法实例名
        Consumer<String> con1=ps::println;
        Consumer<String> con2=System.out::println;
        con1.accept("无风不起浪");
    }

    //2.类名::静态方法名
    @Test
    public void test2(){
        BiFunction<Integer,Integer,Integer> bf=(x,y) ->Math.min(x,y);
        System.out.println("最小值为:"+bf.apply(10,20));
        //Lambda表达式
        BiFunction<Integer,Integer,Integer> bf1=Math::min;
        System.out.println("最小值为:"+bf1.apply(1,2));

    }


    //3.类名::实例方法名
    @Test
    public void test3(){
        //1.Lambda
        BiPredicate<String,String> bp=(str1,str2) ->str1.equals(str2);
        System.out.println(bp.test("hello","hello"));
        //2.方法的引用:有两个参数的情况
        BiPredicate<String,String> bp1=String::equals;
        System.out.println(bp1.test("duibuqi","hello"));
        //2.1方法的引用:只有一个参数
        Function<TestLambda,String> fun=TestLambda::sayHi;
        System.out.println(fun.apply(new TestLambda()));

    }
    public String sayHi(){
        System.out.println("自定义方法");
        return "hi";
    }


    //构造器引用
    @Test
    public void test4(){
        //调用无参构造方法,获取一个实例
        employee emp=new employee();
        //Lambda
        Supplier<employee> sup=() -> new employee();//new employee():无参
        System.out.println(sup.get());

        //构造器引用
        //匹配 无参构造方法
        Supplier<employee> sup1=employee::new;//Supplier:无参
        System.out.println(sup.get());

        //有参数时,匹配带一个字符串的构造方法,并返回
        Function<String,employee> fun=employee::new;
        System.out.println(fun.apply("admin"));

    }

    //数组引用
    @Test
    public void test5(){
        int[] nums=new int[10];
        //Lambda
//        Function<Integer,Integer[]> fun=(x) ->new Integer[x];
        Function<Integer,int[]> fun=(x) ->new int[x];
        System.out.println(fun.apply(5).length);
        //数组引用
        Function<Integer,int[]> fun1=int[]::new;
        int[] num=fun1.apply(10);
        System.out.println("数组的长度为:"+num.length);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值