Lambda Function函数替换If else

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

java8 lambda function函数来替换if else:

但是方法实现过多 还是建议策略模式


提示:简单demo,下面案例可供参考

相关代码

@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行

//创建map并 初始化映射关系
    private static Map<String, Function<Map<String, Object>, Integer>> dispatcher = Maps.newHashMap();
    //定义方法的类型 if else的条件
    private static String TYPE_ONE = "one";
    private static String TYPE_TWO = "two";
    private static String TYPE_THR = "thr";

    @PostConstruct
    public void initDispatcher() {
        dispatcher.put(TYPE_ONE, this::methodOne);
        dispatcher.put(TYPE_TWO, this::methodTwo);
        dispatcher.put(TYPE_THR, this::methodThr);
    }

	//入参map也可以替换为Vo
    public Integer methodOne(Map<String, Object> map) {
        log.info("methodOne,map:{}", JacksonUtil.mapToJson(map));
        return 1;
    }

    public Integer methodTwo(Map<String, Object> map) {
        log.info("methodTwo,map:{}", JacksonUtil.mapToJson(map));
        return 2;
    }

    public Integer methodThr(Map<String, Object> map) {
        log.info("methodThr,map:{}", JacksonUtil.mapToJson(map));
        return 3;
    }
    //使用方法
    public Integer test() {
    	//type相当于if条件 或者switch 中case条件
        String type = TYPE_ONE;
        //获取对应的方法
        Function<Map<String, Object>, Integer> mapIntegerFunction = dispatcher.get(type);
        //参数组装
        Map<String, Object> map = new HashMap<>();
        map.put("param","test");
        map.put("param2","test2");
        //执行方法
        Integer apply = mapIntegerFunction.apply(map);
        log.info("测试结果,apply:{}",apply);
        return apply;
    }

使用方法

    @RequestMapping("/testlambda")
    public Integer test() {
        String type = TYPE_ONE;
        Function<Map<String, Object>, Integer> mapIntegerFunction = dispatcher.get(type);
        Map<String, Object> map = new HashMap<>();
        map.put("param","test");
        map.put("param2","test2");
        Integer apply = mapIntegerFunction.apply(map);
        System.out.println(apply);
        return apply;
    }

测试方法执行结果

在这里插入图片描述


总结

简单的java8 lambda function函数来替换if else代码demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值