Optional conversion from Guava to Java
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));
}
How about Optional javaOpt = Optional.ofNullable(guavaOpt.orNull());
?
Use guava transformation
maybeSomething
.transform(java.util.Optional::of).or(java.util.Optional.empty());