Optionally getting field

后端 未结 2 1721
执念已碎
执念已碎 2020-12-11 03:46

I have a class structure like this:

public class Foo {
    private FooB foob;

    public Optional getFoob() {
        return Optional.ofNullable         


        
2条回答
  •  臣服心动
    2020-12-11 04:19

    What you are describing is the method Optional.map:

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

    map lets you transform the value inside an Optional with a function if the value is present, and returns an empty 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().

提交回复
热议问题