如何使用for迭代Java中的流? [英] How do I iterate over a stream in Java using for?
本文介绍了如何使用for迭代Java中的流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
List<String> strings = Arrays.asList("a", "b", "cc");
for (String s : strings) {
if (s.length() == 2)
System.out.println(s);
}
我想用过滤器和lambda来编写它:
I want to write it using a filter and a lambda:
for (String s : strings.stream().filter(s->s.length() == 2)) {
System.out.println(s);
}
我得到只能迭代数组或者java.lang.Iterable的实例
。
我试试:
for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {
System.out.println(s);
}
我得到同样的错误。这有可能吗?我真的不想做stream.forEach()并传递消费者。
And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.
编辑:对我来说不要复制元素很重要。
it's important to me not to copy the elements.
推荐答案
你需要一个iterable才能使用for-each循环,例如一个集合或一个数组:
You need an iterable to be able to use a for-each loop, for example a collection or an array:
for (String s : strings.stream().filter(s->s.length() == 2).toArray(String[]::new)) {
或者,您可以完全摆脱for循环:
Alternatively, you could completely get rid of the for loop:
strings.stream().filter(s->s.length() == 2).forEach(System.out::println);
你提到你不想重构你的for循环但是你可以用另一种方法提取它的身体:
You mention you don't want to refactor your for loop but you could extract its body in another method:
strings.stream().filter(s->s.length() == 2).forEach(this::process);
private void process(String s) {
//body of the for loop
}
这篇关于如何使用for迭代Java中的流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文