Java 8 Optional asSet()

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

You appear to only be using asSet so you can write a for loop, but that's unnecessary in Java 8. Instead of your code

Optional<User> optUser = getUserOptional();
if ( optUser.isPresent() ) {
    return optUser.get().isPermitted(getPermissionRequired());
}

you could write

getUserPresent().map(optUser -> optUser.isPermitted(getPermissionRequired()))
   .orElse(false);

...or, in many cases, you could use Optional.ifPresent(Consumer<T>).


You can use map :

return optUser.map(u -> u.isPermitted(getPermissionRequired()));

But it would return an Optional<WhateverTypeIsPermittedReturns>.

Reference

public Optional map(Function mapper)

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.