Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

lambda - If not null - java 8 style

Java 8 presents Optional class.

Before (Java 7):

Order order = orderBean.getOrder(id);
if (order != null) {
    order.setStatus(true);
    pm.persist(order);
} else {
    logger.warning("Order is null");
}

So on Java 8 style:

Optional<Order> optional = Optional.ofNullable(orderBean.getOrder(id));
optional.ifPresent( s -> {
    s.setStatus(true);
    pm.persist(s);
    //Can we return from method in this place (not from lambda) ???
});
//So if return take place above, we can avoid if (!optional.isPresent) check
if (!optional.isPresent) {
    logger.warning("Order is null");
} 

Is it correct to use Optional in this case? Can anyone propose a more convenient way in Java 8 style?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...