【问题标题】:continue doesn't work when using streams and the map使用流和地图时继续不起作用
【发布时间】: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&lt;Long&gt; getIds(final Long[][] value) { return Arrays.stream(value) .map(result -&gt; result[1]) // AIOBE possible!! .filter(Objects::nonNull) .collect(Collectors.toList()); }

标签: java for-loop if-statement java-8 java-stream


【解决方案1】:

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

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

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

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

我第一个由@Holger 提出的方法的另一个更优雅的版本是使用filter 中的谓词:

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

【讨论】:

  • 虽然Stream.ofNullable 中的flatMap(使用Java-9)会提高代码的可读性。我不明白,正如其中一个 cmets 所指出的那样,映射和过滤有什么危害?我相信那会更干净。
  • @dernor00 怎么说呢,听起来不像程序员?它对我有用:List&lt;Long&gt; list = Arrays.stream(new Long[][]{{1L, 2L},{3L, 4L}}).flatMap(result -&gt;{ final Long id = result[1]; return Stream.ofNullable(id); }).collect(Collectors.toList());
  • @Andronicus 谢谢你,我知道我的错误在哪里。这是因为我忘记使用 .flatMap() 但我保留了 .map()。现在它适用于您的旧版本和新版本:)
  • ..或者更简单的.flatMap(result -&gt; Stream.ofNullable(result[1]))
  • “用return关键字显示答案”有什么好处?这只是.flatMap(result -&gt; Stream.ofNullable(result[1])) 的详细版本。那么为什么不使用@Naman 的 Java 8 兼容 .map(a -&gt; a[1]).filter(Objects::nonNull)...
猜你喜欢
  • 1970-01-01
  • 2017-04-18
  • 2016-05-02
  • 1970-01-01
  • 2018-09-12
  • 2017-04-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多