Demystifying Java Streams: Step‑by‑Step Code Walkthrough
This article breaks down Java Stream usage by dissecting each line of a sample program, comparing it with equivalent non‑stream code, and illustrating how iterate, limit, map, filter, and reduce work together to produce the final result.
1. Stream Example Code Analysis
This Stream code consists of five lines; we examine each line.
Line 1
The line contains two parts: a lambda expression and the Stream.iterate() call. num -> num + 4 This lambda adds 4 to its input, equivalent to:
int addFour(int num) {
return num + 4;
} Stream.iterate(4, num -> num + 4)creates an infinite stream starting at 4, where each subsequent element adds 4, producing:
4, 8, 12, 16, 20, 24, 28, …Line 2
The limit() operation works like SQL's LIMIT, restricting the infinite stream to a finite number of elements. With total = 5, the stream becomes:
4, 8, 12, 16, 20Line 3
The map() operation applies a lambda that squares each element, transforming the stream to:
4*4, 8*8, 12*12, 16*16, 20*20 => 16, 64, 144, 256, 400Line 4
The filter() step keeps only elements divisible by 10; in this case only 400 remains:
400Line 5
The reduce() operation aggregates the stream. Starting from 0, it sums all elements, yielding the final result:
From 0, calculate the sum of all stream elements and return the accumulated value.
The Stream therefore returns 400 .
2. Code Comparison for Understanding
To make the Stream logic clearer, we rewrite the same computation using ordinary loops:
Key correspondences: Stream.iterate() initial value ↔ loop initialization.
Second argument (lambda) ↔ loop body operation. limit() ↔ loop termination condition (based on element count). map() ↔ square calculation inside the loop. filter() ↔ if statement inside the loop. reduce() ↔ accumulation variable, update, and final return.
With this side‑by‑side analysis, the behavior of Java Streams becomes easier to grasp.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
