How to make java 8 Stream map continuously with null check
Add condition in filter
if list is not null and i.isIsmain
then only filter, you can use public static boolean isNull(Object obj)
or public static boolean nonNull(Object obj)
Coverage mainCoverage = illus.getLifes().stream()
.filter(i->i.isIsmain && Objects.nonNull(i.getCoverages()))
.findFirst()
.orElseThrow(() -> new ServiceInvalidAgurmentGeneraliException(env.getProperty("MSG_002")))
.getCoverages()
.stream() // <==may cause null here if list coverage is null
.filter(Coverage::isMainplan)
.findFirst()
.orElseThrow(() -> new ServiceInvalidAgurmentGeneraliException(env.getProperty("MSG_002")));
Life::getCoverages
returns a collection hence the filter Coverage::isMainplan
will not work, instead you should flatMap
the sequences returned after .map(Life::getCoverages)
then apply the filter
operation on the Coverage
:
Coverage mainCoverage =
illus.getLifes()
.stream()
.filter(Life::isIsmain)
.map(Life::getCoverages)
//.filter(Objects::nonNull) uncomment if there can be null lists
.flatMap(Collection::stream) // <--- collapse the nested sequences
//.filter(Objects::nonNull) // uncomment if there can be null Coverage
.filter(Coverage::isMainplan)
.findFirst().orElse(...);
I've added a few things to your code:
- I've added
.filter(Objects::nonNull)
after.map(Life::getCoverages)
which you can uncomment given the elements returned could potentially be null. - I've added
.flatMap(Collection::stream)
which returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. - I've added another
.filter(Objects::nonNull)
which you can uncomment given the elements returned afterflatMap
could potentially be null. - We're then at a stage in which we can apply
.filter(Coverage::isMainplan)
and finally, retrieve the first object meeting the criteria viafindFirst
and if none then provide a default value viaorElse
.
I'd suggest having a look at the following blogs to get familiar with the flatMap
method:
- Java 8 flatMap example
- Understanding flatMap
- A Guide to Streams in Java 8: In-Depth Tutorial with Examples