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 ?
 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())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With