Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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 ?

like image 833
AshwinK Avatar asked May 15 '19 11:05

AshwinK


1 Answers

 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())
like image 165
Eugene Avatar answered Oct 11 '22 13:10

Eugene