如何使用 for 迭代 Java 中的流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31044041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:34:25  来源:igfitidea点击:

How do I iterate over a stream in Java using for?

javaforeachlambdajava-8java-stream

提问by ytoledano

I have this code:

我有这个代码:

List<String> strings = Arrays.asList("a", "b", "cc");
for (String s : strings) {
    if (s.length() == 2)
        System.out.println(s);
}

I want to write it using a filter and a lambda:

我想使用过滤器和 lambda 来编写它:

for (String s : strings.stream().filter(s->s.length() == 2)) {
    System.out.println(s);
}

I get Can only iterate over an array or an instance of java.lang.Iterable.

我明白了Can only iterate over an array or an instance of java.lang.Iterable

I try:

我尝试:

for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {
    System.out.println(s);
}

And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.

我得到了同样的错误。这甚至可能吗?我真的不想做 stream.forEach() 并传递消费者。

Edit: it's important to me not to copy the elements.

编辑:对我来说不要复制元素很重要。

采纳答案by assylias

You need an iterable to be able to use a for-each loop, for example a collection or an array:

您需要一个可迭代对象才能使用 for-each 循环,例如集合或数组:

for (String s : strings.stream().filter(s->s.length() == 2).toArray(String[]::new)) {

Alternatively, you could completely get rid of the for loop:

或者,您可以完全摆脱 for 循环:

strings.stream().filter(s->s.length() == 2).forEach(System.out::println);

You mention you don't want to refactor your for loop but you could extract its body in another method:

你提到你不想重构你的 for 循环,但你可以用另一种方法提取它的主体:

strings.stream().filter(s->s.length() == 2).forEach(this::process);

private void process(String s) {
  //body of the for loop
}