函数型接口的使用

本文介绍了如何在Java中使用自定义函数型接口TestFunction,并展示了如何将其作为方法参数,包括静态方法和泛型接口的实例。通过实例演示了Test01Function、Test02Function和Test03Function的使用,以及test01到test04的调用结果。
摘要由CSDN通过智能技术生成
  1. 自定义函数型接口
  2. 函数型接口作为方法入参的使用
  3. 类名::类方法在函数型接口中的使用
public interface TestFunction {
    /**
     * 函数型接口的使用
     */
    static void main(String[] args) {
        System.out.println("----------1----------");
        test01(TestFunction::method01);
        test01(()-> System.out.println("test01-hello"));
        System.out.println("----------2----------");
        System.out.println(test02(TestFunction::method02));
        System.out.println(test02(() -> "test02-hello"));
        System.out.println("----------3----------");
        System.out.println(test03(1,TestFunction::method03));
        System.out.println(test03(0,(Integer x) -> x == 0 ? "zero":"not zero"));
        System.out.println(test03_01(0, x -> x == 0 ? "zero":"not zero"));
        System.out.println("----------4----------");
        System.out.println(test04((x,y,z) ->  x * y + z ));
        System.out.println(test04(6,8,9,(Integer x,Integer y, Integer z) ->  x * y + z ));

    }
    
    //自定义函数型接口
    @FunctionalInterface
    interface Test01Function { void get();}

    @FunctionalInterface
    interface Test02Function<X,Y,Z>{ void get(X x, Y y, Z z);}


    @FunctionalInterface
    interface Test03Function<X,Y,Z,M>{ M get(X x, Y y, Z z);}
    

    static void test01(Test01Function function){
        function.get();
    }

    static <T> T test02(Supplier<T> function){
        return function.get();
    }

    static <T,R> R test03(T param, Function<T,R> function){
        return function.apply(param);
    }

    static String test03_01(Integer param, Function<Integer,String> function){
        return function.apply(param);
    }

    static int test04(Test03Function<Integer,Integer,Integer,Integer> function){
        int x = 3 , y= 2 , z = 5;
        return function.get(x,y,z);
    }

    static<X,Y,Z,M> M test04(X x , Y y , Z z, Test03Function<X,Y,Z,M> function){
        return function.get(x,y,z);
    }
    
    static void method01(){
        System.out.println("method01");
    }

    static String method02(){
        return "method02";
    }

    static String method03(Integer i){
        if (i == 0){
            return "zero";
        } else {
            return "not zero";
        }
    }

}

控制台输出

----------1----------
method01
test01-hello
----------2----------
method02
test02-hello
----------3----------
not zero
zero
zero
----------4----------
11
57

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值