How to make conversion from Guava Optional to Java Optional, without usage of any if statements?
if (maybeSomething.isPresent()) {
return java.util.Optional.of(maybeSomething.get())
} else {
return java.util.Optional.empty()
}
Use guava transformation
maybeSomething
.transform(java.util.Optional::of).or(java.util.Optional.empty());
Guava Release 21 introduced the toJavaUtil
and fromJavaUtil
conversion methods to the Optional
class.
javaUtilOptional = Optional.toJavaUtil(guavaOptional);
guavaOptional = Optional.fromJavaUtil(javaUtilOptional);
Under the hood it seems to be implemented largely as the suggestion in Kayaman's answer:
public java.util.Optional<T> toJavaUtil() {
return java.util.Optional.ofNullable(orNull());
}
...
public static <T> Optional<T> fromJavaUtil(@Nullable java.util.Optional<T> javaUtilOptional) {
return (javaUtilOptional == null) ? null : fromNullable(javaUtilOptional.orElse(null));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With