If not null - java 8 style

后端 未结 2 932
攒了一身酷
攒了一身酷 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  void ifPresentOrElse(Optional optional,
            Consumer action, Runnable emptyAction) {
        if (optional.isPresent()) {
            action.accept(optional.get());
        } else {
            emptyAction.run();
        }
    }
    

    And use like this:

    Optional 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"));
    

提交回复
热议问题