How to merge multiple list using flat map with null and empty check in java 8?

AshwinK :

I'm merging multiple list using Stream.of(..) & then performing flatMap on the same to collect the combined list as below:

class Foo{

    List<Entity> list1;
    List<Entity> list2;
    List<Entity> list3;

    //getters & setters

}
Foo foo = getFoo();
Predicate<Entity> isExist = //various conditions on foo ;
List<Bar> bars = Stream
        .of(foo.getList1(), foo.getList2(), foo.getList3())
        .flatMap(Collection::stream)
        .filter(isExist)
        .map(entity -> getBar(entity))
        .collect(Collectors.toList());

First question:

Does Stream.of(..) checks nonNull & notEmpty? If ans is No then,

Second Question:

How can I perform the nonNull & notEmpty checks on all the lists I'm getting from foo in the above code ?So that whenever merge of all these three list happens, it will basically ignore the null & empty list to avoid NullPointerException ?

Eugene :
 Stream
    .of(foo.getList1(), foo.getList2(), foo.getList3())
    .filter(Objects::nonNull)
    ....

Or as pointed by Holger and specified in the flatMap java-doc:

If a mapped stream is null an empty stream is used, instead.

thus, you could do:

 Stream
    .of(foo.getList1(), foo.getList2(), foo.getList3())
    .flatMap(x -> x == null? null : x.stream())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90436&siteId=1