使用流中的Java 8 foreach循环移至下一个项目 [英] Move to next item using Java 8 foreach loop in stream

查看:309
本文介绍了使用流中的Java 8 foreach循环移至下一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java 8流的问题,试图继续循环下一个项目。我不能像 continue; 那样设置命令,只有 return; 有效,但在这种情况下你将退出循环。我需要继续循环下一个项目。我该怎么做?

I have a problem with the stream of Java 8 foreach attempting to move on next item in loop. I cannot set the command like continue;, only return; works but you will exit from the loop in this case. I need to move on next item in loop. How can I do that?

示例(不工作):

try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
            filteredLines = lines.filter(...).foreach(line -> {
           ...
           if(...)
              continue; // this command doesn't working here
    });
}

示例(工作):

try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
    filteredLines = lines.filter(...).collect(Collectors.toList());
}

for(String filteredLine : filteredLines){
   ...
   if(...)
      continue; // it's working!
}


推荐答案

使用 return; 将正常工作。它不会阻止完整循环完成。它只会停止执行 forEach 循环的当前迭代。

Using return; will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach loop.

尝试以下小程序:

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    stringList.stream().forEach(str -> {
        if (str.equals("b")) return; // only skips this iteration.

        System.out.println(str);
    });
}

输出:


a
c

a
c

注意如何返回;对 b 迭代执行,但 c 在下一次迭代中打印就好了。

Notice how the return; is executed for the b iteration, but c prints on the following iteration just fine.

这种行为最初看起来不直观的原因是因为我们习惯了 return 语句中断整个方法的执行。所以在这种情况下,我们希望停止 main 方法执行。

The reason the behavior seems unintuitive at first is because we are used to the return statement interrupting the execution of the whole method. So in this case, we expect the main method execution as a whole to be halted.

然而,需要什么要理解的是lambda表达式,例如:

However, what needs to be understood is that a lambda expression, such as:

str -> {
    if (str.equals("b")) return;

    System.out.println(str);
}

...确实需要被视为自己独特的方法,完全独立于 main 方法,尽管它位于其中。实际上, return 语句只会暂停lambda表达式的执行。

... really needs to be considered as its own distinct "method", completely separate from the main method, despite it being conveniently located within it. So really, the return statement only halts the execution of the lambda expression.

第二件事需要是理解的是:

The second thing that needs to be understood is that:

stringList.stream().forEach()

...实际上只是在每次迭代时执行lambda表达式的正常循环。

... is really just a normal loop under the covers that executes the lambda expression for every iteration.

考虑到这两点,上述代码可以用以下等效方式重写(仅用于教育目的):

With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    for(String s : stringList) {
        lambdaExpressionEquivalent(s);
    }
}

private static void lambdaExpressionEquivalent(String str) {
    if (str.equals("b")) {
        return;
    }

    System.out.println(str);
}

使用这个魔法代码等效的代码,<$ c的范围$ c> return 语句变得更加明显。

With this "less magic" code equivalent, the scope of the return statement becomes more apparent.

这篇关于使用流中的Java 8 foreach循环移至下一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆