使用流和地图时继续不起作用

der*_*r00 3 java for-loop if-statement java-8 java-stream

我有这个简单的代码,我在其中使用了一个流和一个 .map() 函数。我对 id 进行空检查,并在其中添加一个continue 继续给我一个错误:在循环外继续 当我删除 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());
}
Run Code Online (Sandbox Code Playgroud)

关于.streams为什么会发生这种情况的任何建议?而当我不使用流时,我可以使用continue

该问题已被标记为重复,但事实并非如此。使用return肯定适用于forEach,其中不要求返回类型,但不适用于map

And*_*cus 6

continue在 for 循环中工作。您可以将其flatMap用作解决方法:

 List<Long> list = Arrays.stream(value).flatMap(result ->{
            final Long id = result[1];
            return Stream.ofNullable(id);
        }).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

您还可以Stream.ofNullable按照@Naman 的建议直接使用,使其更加简洁:

 List<Long> list = Arrays.stream(value)
    .flatMap(result -> Stream.ofNullable(result[1]))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

@Holger 我首先提出的方法的另一个更优雅的版本是在 中使用谓词filter

 List<Long> list = Arrays.stream(value)
    .map(result -> result[1])
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 尽管“flatMap”(使用 Java-9)中的“Stream.ofNullable”会提高代码的可读性。我不明白,正如评论之一指出的那样,映射和过滤有什么危害?我相信那会干净得多。 (2认同)
  • ..或更简单的 `.flatMap(result -&gt; Stream.ofNullable(result[1]))` (2认同)
  • “用return关键字显示答案”有什么好处?它只是 `.flatMap(result -&gt; Stream.ofNullable(result[1]))` 的详细版本。那么为什么不使用 @Naman 的 Java 8 兼容 `.map(a -&gt; a[1]).filter(Objects::nonNull)`... (2认同)