Java流:多列表抛出NPE上的嵌套流查找
我在Java 7中有以下代码:Java流:多列表抛出NPE上的嵌套流查找,java,list,collections,java-8,java-stream,Java,List,Collections,Java 8,Java Stream,我在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 inf
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));
}
}
}
List idMappers=new ArrayList();
//从地图上获取信息
List id=idDataStore.lookupId(id);
对于(int i=0;i
我想把这个改成流
List<Integer> idMappers= new ArrayList<>();
idDataStore.lookupIdMappings(id).forEach(id-> {
idDataStore.lookupSegments(id).forEach(mapper->{
idSegments.add(segment);
});
});
List idMappers=new ArrayList();
idDataStore.lookupIdMappings(id).forEach(id->{
idDataStore.lookupSegments(id).forEach(映射器->{
idSegments.add(段);
});
});
我的问题是
idDataStore。lookupSegments(id)
有时会抛出null,因此我的流中断。如何在流中执行空检查?只需向嵌套循环添加idDataStore.lookupSegments(id).Stream().filter(Objects::notNull)
但是,您拥有的是一个(请参见“副作用”部分),不建议使用此方法填充idMappers
列表。让我尝试使用flatMap
List<Integer> idMappers = idDataStore.lookupIdMappings(id)
.stream() // stream of LookupId's
.flatMap(idMapping -> idDataStore
.lookupSegments(id)
.stream()
.filter(Objects::notNull)
// get stream of corresponding lookupSegments
// and filter out all nulls
)
.collect(Collectors.toList());
List idMappers=idDataStore.lookupIdMappings(id)
.stream()//LookupId的流
.flatMap(idMapping->idDataStore
.查找段(id)
.stream()
.filter(对象::notNull)
//获取相应查找段的流
//并过滤掉所有空值
)
.collect(Collectors.toList());
我希望这有帮助 首先,在lambda中使用的变量(id
)不能与方法作用域中的变量同名
Lambda表达式的参数id无法重新声明在封闭范围中定义的另一个局部变量
我看到您使用嵌套循环,为什么不使用流::flatMap
idDataStore.lookupIdMappings(id).stream()
.map(i -> idDataStore.lookupSegments(id))
.filter(Objects::nonNull)
.flatMap(List::stream)
.collect(Collectors.toList());
我从这里尝试了,但没有帮助抛出相同的错误尝试这个
idDataStore.lookupIdMappings(id).stream().map(I->idDataStore.lookupSegments(id)).filter(Objects::nonNull).forEach(s->s.forEach(idSegments::add))代码>