0

So I have something that looks like this:

(String) loginResponse.getGroup().getAdditionalProperties().get(something);

and each and every component of the expression could return null. I want to avoid throwing an exception and checking if null after each call doesn't look like the best way to do it:

   temp= loginResponse.getGroup();
   if(temp!=null){
      temp= temp.getAdditionalProperties()
      if(temp!=null){
         temp.get(something)
      }
   }etc...

What's a better way to do this?

Thanks

1 Answers1

0

you can use "Optional" and chain the call inside a map()

Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseThrow(...)
Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseGet(...)

You avoid nullPointerException by this way. It goes in the orElse... if anly element is null at any places

Beno
  • 21
  • 1