我在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表达式的参数ID无法重新声明在封闭范围内定义的另一个局部变量。


我看到您使用嵌套循环,为什么不使用Stream::flatMap

idDataStore.lookupIdMappings(id).stream()
                                .map(i -> idDataStore.lookupSegments(id))
                                .filter(Objects::nonNull)
                                .flatMap(List::stream)
                                .collect(Collectors.toList());

10-07 13:30
查看更多