So I have been using Guava's Optional for a while now, and I moving to Java 8 so I wanted to use it's 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.
IE
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 aSet
. It works just like any other conversion of anOptional
:Given an
Optional<T> o
you can invoketo get a
Set<T>
. If you don’t like the idea ofCollections.emptySet()
being called in every case you can turn it into a lazy evaluation: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:
You can modify your getUserOptional so that it returns a Set or implement your own asSet method :
or
I don't know if there is a built-in way to do it however.
You can use
map
:But it would return an
Optional<WhateverTypeIsPermittedReturns>
.Reference
You appear to only be using
asSet
so you can write a for loop, but that's unnecessary in Java 8. Instead of your codeyou could write
...or, in many cases, you could use
Optional.ifPresent(Consumer<T>)
.I also don't see a really elegant, built-in way to do this, but would like to propose a solution similar to that of Dici:
This avoids the creation of a new
HashSet
instance and the insertion of the optional object. (Note: This is basically the "inlined" version of what GuavasPresent
andAbsent
classes do: ThePresent
class returns thesingletonSet
, and theAbsent
class returns theemptySet
).The usage would be similar to your original pattern: