If not null - java 8 style

后端 未结 2 919
攒了一身酷
攒了一身酷 2020-12-16 18:35

Java 8 presents Optional class.

Before (Java 7):

Order order = orderBean.getOrder(id);
if (order != null) {
    order.setStatus(true);
          


        
相关标签:
2条回答
  • 2020-12-16 19:01

    Unfortunately, the ifPresentOrElse method you're looking for will be added only in JDK-9. Currently you can write your own static method in your project:

    public static <T> void ifPresentOrElse(Optional<T> optional,
            Consumer<? super T> action, Runnable emptyAction) {
        if (optional.isPresent()) {
            action.accept(optional.get());
        } else {
            emptyAction.run();
        }
    }
    

    And use like this:

    Optional<Order> optional = Optional.ofNullable(orderBean.getOrder(id));
    ifPresentOrElse(optional, s -> {
        s.setStatus(true);
        pm.persist(s);
    }, () -> logger.warning("Order is null"));
    

    In Java-9 it would be easier:

    optional.ifPresentOrElse(s -> {
        s.setStatus(true);
        pm.persist(s);
    }, () -> logger.warning("Order is null"));
    
    0 讨论(0)
  • 2020-12-16 19:11

    //Can we return from method in this plase (not from lambda) ???

    Lambdas do not implement "non-local return" semantics, therefore the answer is no.

    Generally, since you need side-effectful action in both the case where the value is present and not, a branching point in the code is essential—whether you wrap it in some fancy API or not. Also, FP generally helps improve referentially transparent transformations (i.e., code built around pure functions) and not side effects, so you won't find much benefit by going through the Optional API.

    0 讨论(0)
提交回复
热议问题