我在 Java 7 中有以下代码:
List<Integer> idMappers= new ArrayList<>();
//getting information from a Map<String, List<String>>
List<String> ids= idDataStore.lookupId(id);
for (int i = 0; i < ids.size(); i++) {
//getting information from a Map<String, List<Integer>>
List<Integer> mappers= idDataStore.lookupMappers(ids.get(i));
if (mappers!= null) {
for (int j = 0; j < x.size(); j++) {
idMappers.add(mappers.get(j));
}
}
}
我正在尝试将其更改为 Streams
List<Integer> idMappers= new ArrayList<>();
idDataStore.lookupIdMappings(id).forEach(id-> {
idDataStore.lookupSegments(id).forEach(mapper->{
idSegments.add(segment);
});
});
我的问题是 idDataStore.lookupSegments(id)
有时会抛出 null,因此我的流会中断。如何在 Stream 中进行空检查?
最佳答案
首先,lambda 中使用的变量 (id
) 不能与该方法的同一作用域中的变量同名。
Lambda expression's parameter id cannot redeclare another local variable defined in an enclosing scope.
我看到您使用嵌套 for 循环,为什么不使用 Stream::flatMap
?
idDataStore.lookupIdMappings(id).stream()
.map(i -> idDataStore.lookupSegments(id))
.filter(Objects::nonNull)
.flatMap(List::stream)
.collect(Collectors.toList());
关于Java流: Nested Stream lookup Over Multiple List throws NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52610887/