sharath
sharath

Reputation: 3616

Java 8 nested null check and access first element

How can I convert the below legacy java code to use Optional :

if (outer != null
        && outer.getInnerMethod() != null
        && outer.getInnerMethod().isAllowed()) {
   Obj value = outer.getInnerMethod().getSomethingElse();
}

Using something like Optional.ofNullable took me till here -

Optional.ofNullable(Outer.getOuter)
        .map(Outer::getInnerMethod)
        .map(SomethingElse::isAllowed)
        .ifPresent(.. );

But ifPresent will not have access to the outer object. What would be the cleanest way to transform something like this ?

Upvotes: 1

Views: 78

Answers (3)

Under_Koen
Under_Koen

Reputation: 1078

Instead of using map to chech if it's allowed use filter(e -> e.isAllowed()) this will filter out anything that isn't allowed.

Upvotes: 1

Lino
Lino

Reputation: 19926

Use filter instead of map. From the java doc

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.

Optional<Obj> optional = Optional.ofNullable(Outer.getOuter)
    .map(Outer::getInnerMethod)
    .filter(SomethingElse::isAllowed)
    .map(SomethingElse::getSomethingElse);

Upvotes: 1

Kunal Vohra
Kunal Vohra

Reputation: 2846

Do this

Optional.ofNullable(Outer.getOuter)
        .filter(outer -> ::Objects.nonNull(outer.getInnerMethod()))
        .filter(SomethingElse::isAllowed)
        .map (.. ); //or whatever operation you want to do here

Upvotes: 2

Related Questions