Java流中的中间操作 [英] Intermediate operation in Java streams
本文介绍了Java流中的中间操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 8中,我使用Streams打印输出,但大小即将为0.为什么?
In java 8, I am using Streams to print the output, but size is coming as 0. Why?
public class IntermediateryAndFinal {
public static void main(String[] args) {
Stream<String> stream = Stream.of("one", "two", "three", "four", "five");
Predicate<String> p1 = Predicate.isEqual("two");
Predicate<String> p2 = Predicate.isEqual("three");
List<String> list = new ArrayList<>();
stream.peek(System.out::println)
.filter(p1.or(p2))
.peek(list::add);
System.out.println("Size = "+list.size());
}
}
推荐答案
理想情况下,您不应更改外部列表,而可以使用 Collectors.toList()
将其收集在列表中:
Ideally you should not mutate an external list, instead you can use Collectors.toList()
to collect it in a list:
List<String> list = stream.peek(System.out::println)
.filter(p1.or(p2))
.collect(Collectors.toList()); // triggers the evaluation of the stream
System.out.println("Size = "+list.size());
在您的示例中,仅当像
allMatch()
anyMatch()
noneMatch()
collect()
count()
forEach()
min()
max()
reduce()
遇到
.
这篇关于Java流中的中间操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文