Optional field retrieval

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 int valA;

    public int getValA() {
        return valA;
    }
}

My goal is to call the get method for fooBand then check if it is present. If present, return the property valAif it does not return, and then just return null. So something like this:

Integer valA = foo.getFoob().ifPresent(getValA()).orElse(null);

Of course, this is not the correct Java 8 syntax, but my "psuedo code". Is there a way to achieve this in Java 8 with 1 line?

+4
source share
2 answers

What you are describing is a method map:

Integer valA = foo.getFoob().map(f -> f.getValA()).orElse(null);

mapallows you to convert the value inside Optionalusing the function if it is present, and only changes the type of optional if the value is missing.

, null , Optional.empty().

+15

getValue Foo? .

public class Foo {
   ...
   public Integer getValue() {
       if (foob == null) {
          return null;
       }
       return foob.getValA();
   }
}
+1

All Articles