Optionally getting field

2020-02-06 07:24发布

问题:

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 objective is to call the get method for fooB and then check to see if it's present. If it is present then return the valA property, if it doesn't then just return null. So something like this:

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

Of course this isn't proper Java 8 optional syntax but that's my "psuedo code". Is there any way to achieve this in Java 8 with 1 line?

回答1:

What you are describing is the map method:

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

map lets you transform the value inside an Optional with a function if the value is present, and only changes the type of the optional if the value in not present.

Note also that you can return null from the mapping function, in which case the result will be Optional.empty().



回答2:

Why you dont add a getValue methode to the class Foo? This would be a kind of delegation.

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