Java 8中的 Function接口

使用注解@FunctionalInterface标识,并且只包含一个抽象方法的接口是函数式接口。函数式接口主要分为Supplier供给型函数、Consumer消费型函数、Runnable无参无返回型函数和Function有参有返回型函数
1、接口类

//1、
@FunctionalInterface
public interface TestException {
    void throwMessage(String message);
}

//2、
@FunctionalInterface
public interface TestConsumer {
    /**
     * 值不为空时执行消费操作
     * 值为空时执行其他的操作
     *
     * @return void
     **/
    void presentOrElseHandle(Consumer action, Runnable emptyAction);
}

//3、
@FunctionalInterface
public interface TestRunable {
    /**
     * Runable类型
     *
     * @param trueHandle 为true时要进行的操作
     * @param falseHandle 为false时要进行的操作
     * @return void
     **/
    void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);
}

2、工具类

public class VUtils {

    public static TestConsumer presentOrElseHandle(boolean flag){
        return (consumer,handler) -> {
            if (flag){
                consumer.accept(flag);
            }else {
                handler.run();
            }
        };
    }

    public static TestException isTrue(boolean flag){
        return (errorMsg) -> {
            if (flag){
                throw new RuntimeException(errorMsg);
            }
        };
    }

    public static TestRunable trueOrFalse(boolean flag){
        return (trueHandle,falseHandle) -> {
            if (flag){
                trueHandle.run();
            }else {
                falseHandle.run();
            }
        };
    }

}

3、测试类

public class TestFun {
    public static void main(String[] args) {
        //1、
        VUtils.isTrue(true).throwMessage("c");
        //2、
        VUtils.trueOrFalse(false).trueOrFalseHandle(()->{
            System.out.println("==true==");
        },()->{
            System.out.println("==false==");
        });
        //3、
        VUtils.presentOrElseHandle(false).presentOrElseHandle(System.out::println,()->{
            System.out.println("false");
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunnyboy_4

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值