Java使用Lambda表达式实现Function <T,R>接口

Function <T,R>接口是java.util.function包中的函数接口。此接口需要一个参数作为输入并生成结果。Function <T,R>接口可用作lambda 表达式或方法引用的分配目标。它包含一个抽象方法:apply(),两个默认方法:andThen()和compose() 以及一个静态方法:identity()。

其中占位符T(type)代表入参类型,R(return)代表返回类型

Function<Integer, Integer> times2 = e -> e * 2;
        Function<Integer, Integer> squared = e -> e * e;
         
        //将参数代入(10*2=20)
        Integer apply2 = times2.apply(10);

        //在times2函数执行之前先执行squared函数 (先运行 4*4=16 再 16*2=32)
        Integer apply = times2.compose(squared).apply(4);

        //在times2执行之后,再执行squared函数 (先运行4*2=8 再8*8=64)
        Integer apply1 = times2.andThen(squared).apply(4);
        
        //直接返回传入的参数
        Function<String, String> fun1 = Function.identity();
        String str1 = fun1.apply("helloWorld");
 
        System.out.println("apply == " + apply); //apply == 32
        System.out.println("apply1 == " + apply1); //apply1 == 64
        System.out.println("apply2 == " + apply2); //apply2 == 20
        System.out.println(str1); //helloWorld
    apply方法是将入参带入方法中 compose()括号中的内容在调用函数time2之前运行 4*4=16 16*2 =32 andThen()括号中的内容在调用函数time2结束之后运行 4*2 =8 8*8=64 identity() 方法直接返回传入的参数
经验分享 程序员 微信小程序 职场和发展