3

I have a class structure like this:

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;
    }
}

What I want to do is something like this:

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

Basically if the foo object returns FooB as present then get the field String a from FooB and store it in the local variable String a. How can I do this elegantly in 1 line?

Richard
  • 5,840
  • 36
  • 123
  • 208
  • 5
    The question is: what do you want to happen if `Optional` is empty? That is exactly what Optional is for: force you to think about that case. – Tunaki Aug 04 '16 at 17:50
  • 1
    `ifPresent()` needs a consumer which cannot return anything. While you could give it a stateful consumer it is most likely better to read to use `map()`. You just need to deal with the resulting `Optional` again: `String a = foo.getFooB().map(FooB::getA).orElse(null);` – eckes Aug 04 '16 at 18:06

2 Answers2

8

As getFooB() returns an instance of Optional<FooB>, to get the corresponding value of getA(), you need to use the map method as next:

Optional<String> a = foo.getFooB().map(FooB::getA);
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
-4
String a = foo.getFooB().isPresent() ? foo.getFooB().get().getA() : {absolutely anything your heart desires if FooB doesn't exist};
John K
  • 462
  • 2
  • 11