我使用Stream.of(..)&合并多个列表,然后flatMap在同一列表上执行以下操作以收集合并的列表,如下所示:
class Foo{
List<Entity> list1;
List<Entity> list2;
List<Entity> list3;
//getters & setters
}
Run Code Online (Sandbox Code Playgroud)
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());
Run Code Online (Sandbox Code Playgroud)
第一个问题:
会Stream.of(..)检查 nonNull&notEmpty吗?如果ans 否,
第二个问题:
我怎样才能对上面代码中得到的所有内容执行nonNull&notEmpty检查?因此,只要这三个列表全部合并,它基本上会忽略&避免?listsfoonullempty listNullPointerException
Stream
.of(foo.getList1(), foo.getList2(), foo.getList3())
.filter(Objects::nonNull)
....
Run Code Online (Sandbox Code Playgroud)
或由Holger指出并在flatMapjava-doc中指定:
如果映射流为null,则使用空流。
因此,您可以执行以下操作:
Stream
.of(foo.getList1(), foo.getList2(), foo.getList3())
.flatMap(x -> x == null? null : x.stream())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |