So I have been using Guava's Optional
for a while now, and I'm moving to Java 8 so I wanted to use its Optional
class, but it doesn't have my favorite method from Guava: asSet()
. Is there a way to do this with the Java 8 Optional
that I am not seeing. I love being able to treat Optional
as a collection so I can do this:
for (final User u : getUserOptional().asSet()) {
return u.isPermitted(getPermissionRequired());
}
In some cases avoids the need for an additional variable.
For example:
Optional<User> optUser = getUserOptional();
if (optUser.isPresent()) {
return optUser.get().isPermitted(getPermissionRequired());
}
Is there an easy way to replicate the Guava style in Java 8's Optional
?
Thanks
There is a simple way of converting an Optional
into a Set
. It works just like any other conversion of an Optional
:
Given an Optional<T> o
you can invoke
o.map(Collections::singleton).orElse(Collections.emptySet())
to get a Set<T>
. If you don’t like the idea of Collections.emptySet()
being called in every case you can turn it into a lazy evaluation:
o.map(Collections::singleton).orElseGet(Collections::emptySet)
however, the method is too trivial to make a performance difference. So it’s just a matter of coding style.
You can also use it to iterate like intended:
for(T t: o.map(Collections::singleton).orElse(Collections.emptySet()))
// do something with t, may include a return statement