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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With