Skip to content

Commit 82556ae

Browse files
committed
feat(streams): demonstrate parallelStream transformations with map, filter, distinct, and sorted
What - Added `Test.java` showcasing multiple parallel stream operations: - Squaring numbers (`map(x -> x*x)`). - Filtering even numbers (`filter(x -> x % 2 == 0)`). - Dividing even numbers by 2 (`map(x -> x/2)`). - Combining `map`, `distinct`, and `sorted` for ordered unique results. - Collected results using `Collectors.toList()` for easy inspection. Why - Parallel streams in Java 8+ allow data processing across multiple CPU cores with minimal code changes. - Demonstrates common transformations (`map`, `filter`, `distinct`, `sorted`) under parallel execution. - Reinforces difference between declarative, functional pipeline vs imperative loops. Logic 1. **Squaring numbers** - Input: `[1..10]` - Pipeline: `parallelStream().map(x -> x*x)` - Output: `[1,4,9,16,25,36,49,64,81,100]` 2. **Filtering even numbers** - Predicate: `x % 2 == 0` - Output: `[2,4,6,8,10]` 3. **Custom transformation (divide evens by 2)** - Filter evens, then `map(x -> x/2)` - Output: `[1,2,3,4,5]` 4. **Distinct + sorted after doubling** - Multiply each element by 2 - Ensure uniqueness with `distinct()` - Order results with `sorted()` - Output: `[2,4,6,8,10,12,14,16,18,20]` Key points - `parallelStream()` automatically partitions work across CPU cores. - Order of elements in intermediate pipelines may vary, but `sorted()` restores deterministic ordering. - `distinct()` ensures uniqueness (useful for deduplication in parallel pipelines). - Collectors unify results into a single collection after parallel execution. Real-world applications - Squaring/transformation → numerical simulations, matrix computations. - Filtering → selecting relevant DB/API results in multi-core processing. - Distinct + sorted → deduplication and ordering of large log or transaction datasets. - Parallel pipelines → speed up analytics in back-end systems with large data sets. Notes - Parallel streams use the common ForkJoinPool with `Runtime.getRuntime().availableProcessors()` threads. - Avoid side effects or shared mutable state in lambdas; correctness may break under parallel execution. - Best for CPU-intensive, independent tasks on medium-to-large datasets. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 32a23f1 commit 82556ae

File tree

1 file changed

+0
-1
lines changed
  • Java 8 Crash Course/Java 8 Streams/Parallel Streams/src

1 file changed

+0
-1
lines changed

Java 8 Crash Course/Java 8 Streams/Parallel Streams/src/Test.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,3 @@ public static void main(String[] args) {
4343
System.out.println("Distinct + Sorted (Parallel): " + distinctSortedParallel);
4444
}
4545
}
46-

0 commit comments

Comments
 (0)