Java 8 Stream末尾count()方法的作用及代码执行疑问
count() in Your Stream Pipeline Great question! Let's break down exactly what count() is doing in your code, since it's playing two key roles here:
1. It triggers execution of the entire Stream pipeline
Streams in Java use lazy evaluation for intermediate operations (like iterate(), peek(), filter(), and limit()). This means these operations don't do any actual work when you define them—they just set up a blueprint for processing data.
A terminal operation (like count(), forEach(), or collect()) is required to kick off the entire pipeline. In your code, count() is that trigger: without it, none of your peek() print statements would run, and no numbers would be generated or filtered. That's why you only see the output once you add count() to the end.
2. It counts the final number of elements in the stream
Beyond triggering execution, count()'s core job is to return the total number of elements that make it through all your intermediate operations. Let's map this to your code:
Stream.iterate(1, n -> n + 1)generates an infinite sequence of positive integersfilter(n -> n % 2 == 0)keeps only even numberslimit(5)stops processing after the first 5 even numbers are found
So count() will tally those 5 even numbers, and return the result 5 (if you assigned the result to a variable like long total = ...count();, printing total would show you this value).
Why your output looks the way it does
Because count() triggers the pipeline, each element goes through the full process:
- A number is generated (triggering the first
peek()print) - It's checked against the filter condition
- If it's even, the second
peek()runs - This repeats until 5 even numbers are collected, then
count()returns their total.
内容的提问来源于stack exchange,提问作者Issam Bakrim

