Commit 2d5139e
committed
feat(streams): add factorial computation and filter-peek-count demo using Java Streams
What
- Added `FactorialDemo`:
- Demonstrates computing factorial using Java 8 Streams (`IntStream.rangeClosed` + `reduce`).
- `printFactorial(int n)` → calculates factorial by reducing the range [1..n] with multiplication.
- `solve(int n)` wrapper method introduced for readability.
- Prints factorial of `6` → output `720`.
- Added `StreamDemo`:
- Demonstrates filtering, peeking, and counting with streams.
- Input list: ["a", "b", "c", "d", "e"].
- `.filter(s -> s.compareTo("c") > 0)` → keeps only elements after "c" alphabetically (`"d"`, `"e"`).
- `.peek(System.out::println)` → prints filtered elements (side effect for debugging).
- `.count()` → terminal operation that counts elements post-filter (expected = `2`).
- Prints elements `"d"`, `"e"`, then the count `2`.
Why
- To illustrate **two key stream use-cases**:
1. **Mathematical computation (factorial)** using `reduce` and `IntStream`.
2. **Data filtering + debugging + aggregation** with filter, peek, and count.
- Reinforces understanding of lazy evaluation (peek prints only when terminal op is triggered).
- Shows declarative programming style vs imperative loops.
Logic
1. **FactorialDemo**
- Stream pipeline: `IntStream.rangeClosed(1, n)` → sequence [1..n].
- Reduce operation: `(a, b) -> a * b` multiplies accumulatively.
- Initial identity = `1` ensures neutral start for multiplication.
- For n=6 → factorial = `1*2*3*4*5*6 = 720`.
2. **StreamDemo**
- List of strings converted to stream.
- Filter keeps strings alphabetically greater than `"c"`.
- Peek prints elements after filter (`"d"`, `"e"`).
- Count triggers evaluation, resulting in `2`.
Key Takeaways
- Streams allow **functional-style computation** (factorial via reduce).
- Intermediate operations (`filter`, `peek`) are lazy → only run when terminal op (`count`) is called.
- `peek()` is invaluable for debugging pipelines without breaking them.
- Terminal operations consume the stream; reuse is not allowed.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent da05615 commit 2d5139e
File tree
1 file changed
+16
-8
lines changed- Java 8 Crash Course/Java 8 Streams/src/Stream
1 file changed
+16
-8
lines changedLines changed: 16 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
1 | 3 | | |
2 | 4 | | |
3 | 5 | | |
4 | | - | |
| 6 | + | |
5 | 7 | | |
6 | 8 | | |
7 | 9 | | |
| |||
17 | 19 | | |
18 | 20 | | |
19 | 21 | | |
20 | | - | |
| 22 | + | |
21 | 23 | | |
22 | 24 | | |
23 | 25 | | |
24 | | - | |
25 | | - | |
26 | | - | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
27 | 35 | | |
28 | 36 | | |
29 | 37 | | |
30 | | - | |
| 38 | + | |
31 | 39 | | |
32 | | - | |
33 | | - | |
| 40 | + | |
| 41 | + | |
0 commit comments