Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...