How to use an additional Java operator to match multiple subtypes

I want to use java optional operator to avoid nullchecks like:

if(outher != null && outher.getNested() != null &&
          outher.getNested().getInner() != null && outher.getNested().getAnotherInner() != null)

I looked through some tutorials in the Internet + Java cheatsheet, but did not find how to resolve the part outher.getNested.getInner() != null && outher.getNested.getAnotherInner != null.

So how to do it right:

Optional.of(outher)
.map(Outher::getNested)
.map(Nested::getInner)
.map(Nested::getAnotherInner)
.isPresent();

will be awesome

+4
source share
2 answers

The problem is that the .map(Nested::getInner)Inner instance is returning, but it should return Outer.

My suggestion:

Optional.ofNullable(outher)
.map(Outher::getNested)
.map((outer) -> outer.getInner() == null ? null : outer)
.map(Nested::getAnotherInner)
.isPresent();

Not sure about flatMap because you have to match the entity on yourself

+3
source

Well, there is a way to use flatmapif you really want:

 boolean result = Optional.ofNullable(outer)
            .map(Outer::getNested)
            .filter(x-> x.getInner() != null)
            .map(Nested::getAnotherInner)
            .isPresent();
+1

Source: https://habr.com/ru/post/1679946/


All Articles