【发布时间】:2020-05-22 18:28:58
【问题描述】:
我有这个简单的代码,我在其中使用了一个流和一个 .map() 函数。 我对 id 进行空值检查,并在其中添加一个 continue continue 给了我一个错误:Continue outside of loop 当我删除 continue 时,我没有收到错误,但我不知道行为是否相同?
public List<Long> getIds(final Long[][] value){
List<Long> list = Arrays.stream(value).map(result ->{
final Long id = result[1];
if(id == null){
continue; // This part doesn't work (error: Continue outside of loop)
}
return id;
}).collect(Collectors.toList());
}
关于为什么 .streams 会发生这种情况的任何建议?然而,当我不使用流时,我可以使用 continue。
问题已被标记为重复,但事实并非如此。使用return 肯定适用于forEach,其中不请求返回类型,但不适用于map。
【问题讨论】:
-
@snnguyen 在
map函数中?我不这么认为 -
@snnguyen 我看到了这个问题,我尝试了
return;它实际上并没有工作 -
当然不行...
map需要函数返回一些东西。 -
@Andronicus 我完全误读了这个问题
-
dernor00 - 很高兴你做到了,你可以简单地使用@JoopEggen 所述的
map。只是一个小的更正将使用nonNull而不是notNull完整的实现看起来像public static List<Long> getIds(final Long[][] value) { return Arrays.stream(value) .map(result -> result[1]) // AIOBE possible!! .filter(Objects::nonNull) .collect(Collectors.toList()); }
标签: java for-loop if-statement java-8 java-stream