Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional conversion from Guava to Java

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()
}
like image 803
Libre13 Avatar asked Nov 25 '15 14:11

Libre13


2 Answers

Use guava transformation

maybeSomething
    .transform(java.util.Optional::of).or(java.util.Optional.empty());
like image 155
MariuszS Avatar answered Oct 13 '22 15:10

MariuszS


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));
}
like image 35
Henrik Aasted Sørensen Avatar answered Oct 13 '22 15:10

Henrik Aasted Sørensen