If not null - java 8 style

Java 8 introduces the 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, 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 Optional correct to use in this case? Can anyone suggest a more convenient way in the style of Java 8?

+7
java lambda java-8 optional
source share
2 answers

Unfortunately, the ifPresentOrElse method you are looking for will only be added to JDK-9. You can currently 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")); 
+6
source share

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

Lambdas does not implement the semantics of "non-local return", so the answer is no.

As a rule, since you need a side effect in both cases when the value is present and not, the branch point in the code is essential: whether you transfer it to some fantastic API or not. In addition, FP usually helps improve link-transparent conversions (i.e. code built on pure functions), rather than side effects, so you won't find much benefit by going through the optional API.

+1
source share

All Articles