有没有一种优雅的方法来打开包裹在 2 个嵌套的 Optionals 中的对象?

Is there an elegant way to unwrap an object wrapped in 2 nested Optionals?

考虑这两个类

class EmailService {
    public Optional<String> getEmailAlias(String email);
}

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

上述方法的实现对问题并不重要,因此为了简单起见,我将其省略。

我想这样做:

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

但是,这不起作用,因为 queueOptional<queue> 类型(与 Queue::fromEmailAlias 返回的类型相同),所以我改为:

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

有点丑陋恕我直言。

正在更改

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

public static Queue fromEmailAlias(String alias);

是一个快速修复,但这也会影响我在其他需要 Optional<Queue>.

的地方的代码

有什么好的方法可以打开这个嵌套的 Optional 吗?

您需要申请flatMap:

emailService.getEmailAlias("john@done")
            .flatMap(Queue::fromEmailAlias)
            .ifPresent(queue -> { 

             });