Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional get if present [duplicate]

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?

like image 692
Richard Avatar asked Feb 10 '26 00:02

Richard


1 Answers

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);
like image 110
Nicolas Filotto Avatar answered Feb 12 '26 16:02

Nicolas Filotto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!