Stream peek May Be Skipped By count
count() returns the known size without running a SIZED pipeline, so peek silently skips; filter destroys the size hint and forces the traversal.
Code
import java.util.List;
import java.util.stream.Collectors;
public class PeekShortCircuit {
public static void main(String[] args) {
List<String> letters = List.of("A", "B", "C", "D");
// 源是 List(SIZED)、peek 不改变元素数:count() 直接返回 4,peek 不执行
long count = letters.stream().peek(e -> System.out.println("seen-count: " + e)).count();
System.out.println("count = " + count);
// map 一对一且不清除 SIZED 标志:count() 依旧走捷径,peek 依旧不执行
long mapped = letters.stream()
.peek(e -> System.out.println("seen-map: " + e))
.map(String::toLowerCase)
.count();
System.out.println("mapped count = " + mapped);
// filter 会清除 SIZED:大小不再可预知,count() 只能真正遍历,peek 逐个执行
long filtered = letters.stream()
.peek(e -> System.out.println("seen-filter: " + e))
.filter(e -> !e.equals("B"))
.count();
System.out.println("filtered count = " + filtered);
// collect 是消费型终端操作:无论标志如何,peek 都会执行
List<String> drained = letters.stream()
.peek(e -> System.out.println("seen-collect: " + e))
.collect(Collectors.toList());
System.out.println("drained: " + drained);
}
}How it works
The moving parts are the class PeekShortCircuit and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
What to watch for
- No dependency resolution happens here; the toolchain alone suffices.
Using it
The main signature, verbatim, is public static void main(String[] args)
The demo output is labeled (seen-count:, count =, seen-map:), so each line traces straight back to the statement that printed it.
The key statements that remain
.collect(Collectors.toList());
long filtered = letters.stream()
.peek(e -> System.out.println("seen-filter: " + e))
.filter(e -> !e.equals("B"))
.count();
long mapped = letters.stream()
.peek(e -> System.out.println("seen-map: " + e))
.map(String::toLowerCase)
.count();
Interactive Tools for This Topic
FAQ
- What does Stream peek May Be Skipped By count print when run?
- Run it as a complete program — the output lines carry labels such as `seen-count:`, `count =`, `seen-map:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.