Is there an elegant way to expand an object wrapped in two nested options?

Consider these two classes

class EmailService { public Optional<String> getEmailAlias(String email); } enum Queue { public static Optional<Queue> fromEmailAlias(String alias); } 

The implementation of the above methods does not matter for the question, so I left this for simplicity.

I want to do this:

 emailService.getEmailAlias("john@done") .map(Queue::fromEmailAlias) .ifPresent(queue -> { // do something with the queue instance, oh wait it an Optional<Queue> :( }); 

However, this does not work because the queue is of type Optional<queue> (the same type as the returned Queue::fromEmailAlias ), so instead:

 emailService.getEmailAlias("john@done") .map(Queue::fromEmailAlias) .ifPresent(q-> { q.ifPresent(queue -> { // do something with the queue instance } }); 

View ugly IMHO.

Signature Change

 public static Optional<Queue> fromEmailAlias(String alias); 

to

 public static Queue fromEmailAlias(String alias); 

is a quick fix, but it will also affect my code in other places that need Optional<queue> .

Is there a good way to deploy this nested optional?

+8
java java-8 optional
source share
1 answer

You need to apply flatMap :

 emailService.getEmailAlias("john@done") .flatMap(Queue::fromEmailAlias) .ifPresent(queue -> { }); 
+13
source share

All Articles