java函数式编程优雅的写if else

前言

我们在写业务代码的时候或多或少会写比较多的if else 进行判断抛出异常、分支处理等操作。这些if...else...充斥在代码中严重影响了代码代码的美观,这时我们可以利用java8的新特性来优雅的写if...else...

if if if 这种结构

原来的写法

String a= "aaa";

if (a.contains("a")) {
    System.out.println("a");
}
if (a.contains("b")) {
    System.out.println("b");
}
System.out.println(a);

现在的写法

BranchUtil.of(a)
        .chain()
        .match(s -> s.equals("bbb")).ifTrue(s -> System.err.println("222"))
        .match(s -> s.equals("aaa")).ifTrue(s -> System.err.println("333"))
        .orElse(s -> System.err.println(s));

 

if else if else if 这种结构

原来的写法

if (a.contains("aaa")) {
    System.out.println("1");
}else if (a.contains("aaa")) {
    System.out.println("2");
}else{
    throw new RuntimeException("未匹配到数据");
}

现在的写法

BranchUtil.of(a)
        .whenIf()
        .match(s -> s.equals("aaa")).ifTrue(s -> System.err.println("111"))
        .match(s -> s.equals("bbb")).ifTrue(s -> System.err.println("wwww"))
        .orElseThrow(() -> ne
  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java函数式编程实现重试的示例代码: ```java public class RetryFunction { public static <T> T retry(Supplier<T> function, int maxAttempts, long delayMillis) throws InterruptedException { int attempts = 0; while (attempts < maxAttempts) { try { return function.get(); } catch (Exception e) { attempts++; if (attempts == maxAttempts) { throw e; } Thread.sleep(delayMillis); } } return null; } } ``` 这个代码使用了Java函数式编程特性Supplier,它可以接受任何没有参数和返回值的函数作为输入,并且可以使用lambda表达式作为函数参数。 `retry`函数接受三个参数:一个函数,最大尝试次数和延迟时间。如果函数执行成功,则返回函数的结果。如果函数抛出异常,则会在延迟一段时间后重试。如果重试次数达到最大值,则会抛出异常。 以下是一个示例使用该函数的代码: ```java public class Main { public static void main(String[] args) throws InterruptedException { String result = RetryFunction.retry(() -> { return fetchDataFromApi(); }, 3, 1000); if (result != null) { System.out.println("Data retrieved successfully: " + result); } else { System.out.println("Failed to retrieve data after multiple retries."); } } private static String fetchDataFromApi() throws IOException { // code to retrieve data from API // if the API call fails, throw an exception throw new IOException("API call failed."); } } ``` 在这个例子中,我们使用了`retry`函数来尝试从API中获取数据。如果API调用失败,则会在延迟1秒后重试,最多重试3次。如果重试次数达到3次,则会打印出失败信息。否则,将打印出成功信息,并显示从API中检索到的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值