【问题标题】:Java Stream : Nested Stream lookup Over Multiple List throws NPEJava Stream:在多个列表上的嵌套流查找抛出 NPE
【发布时间】:2019-03-07 17:32:12
【问题描述】:

我在 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 中进行空检查?

【问题讨论】:

  • 试试这个idDataStore.lookupIdMappings(id) .stream() .map(i -&gt; idDataStore.lookupSegments(id)) .filter(Objects::nonNull) .forEach(s -&gt; s.forEach(idSegments::add));

标签: java list collections java-8 java-stream


【解决方案1】:

首先,在 lambda 中使用的变量 (id) 不能与方法相同范围内的变量同名。

Lambda 表达式的参数 id 不能重新声明在封闭范围内定义的另一个局部变量。

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

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

【讨论】:

    【解决方案2】:

    只需将idDataStore.lookupSegments(id).stream().filter(Objects::notNull) 添加到您的嵌套循环中。

    但是,您拥有的是 side effect(请参阅副作用部分),不推荐填充 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());
    

    我希望这会有所帮助。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多