Java流: Nested Stream lookup Over Multiple List throws NPE

标签 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 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/

相关文章:

java - IllegalArgumentException:创建 SpinnerListModel 时序列元素无效

list - Haskell 得到一个过滤的整数列表

java - java - 如何在Java中构建时使用注释动态生成代码?

java - 尽管保护写操作仍获取竞争条件 - Java

java - 没有找到合适的 add(long) 方法

java - Iterable with size() 的成语 - 在 Iterable 和 Collection 之间?

时间:: how to read from specific index in List<person>

java - 创建扩展哈希集/继承的计数类

java - 在java中从接口(interface)扩展的好处是什么

java - Spark - 如何使用给定权限写入文件