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"));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…