PAA*_*PAA 1 java collections java-8 java-stream
在java 8中,我使用Streams打印输出,但大小为0。为什么?
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());
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,您不应该改变外部列表,而是可以使用Collectors.toList()将其收集到列表中:
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());
Run Code Online (Sandbox Code Playgroud)
在您的示例中,仅当像这样的终端操作时才会评估流
allMatch()
anyMatch()
noneMatch()
collect()
count()
forEach()
min()
max()
reduce()
Run Code Online (Sandbox Code Playgroud)
都遇到了。
| 归档时间: |
|
| 查看次数: |
1516 次 |
| 最近记录: |