Java 8 如果存在可选获取

Java 8 Optional get if present

我有这样的 class 结构:

public class Foo {
    private FooB fooB;

    public Optional<FooB> getFooB() {
        return Optional.ofNullable(fooB);
    }
}

public class FooB {
    private String a;
    private String b;

    public String getA() {
        return a;
    }

    public String getB() {
        return b;
    }
}

我想做的是这样的:

main() {
    //initialize a Foo object called foo
    String a = foo.getFooB().ifPresent(FooB::getA);
}

基本上,如果存在 foo 对象 returns FooB,则从 FooB 获取字段 String a 并将其存储在局部变量 String a 中。我怎样才能在 1 行中优雅地做到这一点?

String a = foo.getFooB().isPresent() ? foo.getFooB().get().getA() : {absolutely anything your heart desires if FooB doesn't exist};

作为getFooB()returnsOptional<FooB>的实例,要得到getA()对应的值,需要使用map方法如下:

Optional<String> a = foo.getFooB().map(FooB::getA);