如何在Java 8中使用带有null和空检查的平面地图合并多个列表?

时间:2019-05-15 11:51:48

标签: java java-8

我正在使用Stream.of(..)合并多个列表,然后在同一列表上执行flatMap以收集合并的列表,如下所示:

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());

第一个问题

Stream.of(..)是否检查nonNullnotEmpty? 如果ans是,则

第二个问题

如何对以上代码中从nonNull获得的所有notEmpty进行listsfoo检查,以便每当合并所有这些内容时发生三个列表时,它将基本上忽略nullempty list以避免NullPointerException吗?

1 个答案:

答案 0 :(得分:5)

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

或者由Holger指出并在flatMap java-doc中指定:

  

如果映射流为null,则使用空流。

因此,您可以这样做:

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