Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...