我正在使用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(..)
是否检查nonNull
和notEmpty
?
如果ans是否,则
第二个问题:
如何对以上代码中从nonNull
获得的所有notEmpty
进行lists
和foo
检查,以便每当合并所有这些内容时发生三个列表时,它将基本上忽略null
和empty
list
以避免NullPointerException
吗?
答案 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())