Skip to content

Commit 8bfab8c

Browse files
committed
feat(streams): add comprehensive demo of intermediate operations in Java Streams
What - Introduced `IntermediateOps.java` to demonstrate all key intermediate operations in Java Streams. - Covered the following with runnable examples: 1. **filter** → select elements matching a predicate. 2. **map** → transform elements (e.g., to uppercase). 3. **sorted** → sort streams (natural & custom comparator). 4. **distinct** → remove duplicates. 5. **limit** → truncate stream size. 6. **skip** → ignore first N elements. 7. **peek** → side-effect actions for debugging/inspection. 8. **flatMap** → flatten nested collections/arrays into a single stream. - Included use cases with lists, infinite streams (`Stream.iterate`), nested lists, and sentence splitting. Why - Intermediate operations are *lazy* by design: they define transformations but do not execute until a terminal op is called. - Many developers confuse "pipeline setup" with execution → this example clarifies the difference. - Demonstrates both stateless (filter, map) and stateful (sorted, distinct) intermediate ops. Logic 1. **filter**: - `list.stream().filter(x -> x.startsWith("A"))` - Builds a pipeline to select elements beginning with "A". - Returns another stream; execution happens only when a terminal op (like `count`) is called. 2. **map**: - Transforms elements without changing stream size. - Example: convert each name to uppercase with `map(String::toUpperCase)`. 3. **sorted**: - Stateful op → must process all elements before emitting. - Demonstrated with both natural order and custom comparator (by length). 4. **distinct**: - Removes duplicate elements based on `equals()`. - Example: distinct names starting with "A". 5. **limit & skip**: - Useful with infinite streams (e.g., `Stream.iterate`). - `limit(100)` produces 100 items. - `skip(10).limit(100)` starts after skipping first 10. 6. **peek**: - Provides visibility into stream pipeline for debugging. - Example: printing elements as they flow through `skip` and `limit`. 7. **flatMap**: - Flattens nested collections (`List<List<String>>`) into a single stream. - Used to: - Convert list-of-lists of fruits into a flat uppercase list. - Split sentences into words and process all words in a single stream. Real-world applications - **Data cleaning pipelines**: filter + map + distinct for deduplication and transformations. - **Pagination logic**: skip + limit for chunked processing. - **Debugging ETL pipelines**: peek to log intermediate results. - **Natural language processing**: flatMap sentences → words for indexing or analytics. - **Sorting/grouping**: sorted as preparation step for reporting dashboards. Notes - Demonstrates how intermediate ops *compose* to build pipelines. - Reinforces that *no actual computation happens until a terminal operation is invoked*. - Aimed as both a runnable tutorial and reference example for declarative stream processing. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent e74b72c commit 8bfab8c

File tree

2 files changed

+67
-61
lines changed

2 files changed

+67
-61
lines changed

JAVA8/StreamsInJAVA/src/IntermediateOps.java

Lines changed: 0 additions & 61 deletions
This file was deleted.
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.util.Arrays;
2+
import java.util.List;
3+
import java.util.stream.Stream;
4+
5+
public class IntermediateOps {
6+
public static void main(String[] args) {
7+
// Intermediate operations transform a Stream into another Stream.
8+
// They are "lazy", meaning they don't execute until a terminal operation is invoked.
9+
10+
// 1. filter → filters elements based on a predicate
11+
List<String> list = Arrays.asList("Akshit", "Ram", "Shyam", "Ghanshyam", "Akshit");
12+
Stream<String> filteredStream = list.stream().filter(x -> x.startsWith("A"));
13+
System.out.println(filteredStream); // Just prints stream object, not data (lazy!)
14+
15+
// Applying a terminal operation (count) → actually triggers filter
16+
long res = list.stream().filter(x -> x.startsWith("A")).count();
17+
System.out.println(res); // Number of elements starting with "A"
18+
19+
// 2. map → transforms each element using a function
20+
Stream<String> stringStream = list.stream().map(String::toUpperCase);
21+
22+
// 3. sorted → sorts elements (stateful operation)
23+
Stream<String> sortedStream = list.stream().sorted(); // natural order
24+
Stream<String> sortedStreamUsingComparator = list.stream()
25+
.sorted((a, b) -> a.length() - b.length()); // custom comparator by length
26+
27+
// 4. distinct → removes duplicates
28+
System.out.println(list.stream().filter(x -> x.startsWith("A")).distinct().count());
29+
30+
// 5. limit → truncates the stream to given size
31+
System.out.println(Stream.iterate(1, x -> x + 1).limit(100).count()); // 100
32+
33+
// 6. skip → skips first 'n' elements
34+
System.out.println(Stream.iterate(1, x -> x + 1).skip(10).limit(100).count()); // 100 (but starts after skipping 10)
35+
36+
// 7. peek → performs an action on each element as it flows (useful for debugging)
37+
Stream.iterate(1, x -> x + 1)
38+
.skip(10)
39+
.limit(100)
40+
.peek(System.out::println) // prints elements as they pass through
41+
.count();
42+
43+
// 8. flatMap → flattens nested structures into a single stream
44+
// Useful when dealing with collections of collections
45+
List<List<String>> listOfLists = Arrays.asList(
46+
Arrays.asList("apple", "banana"),
47+
Arrays.asList("orange", "kiwi"),
48+
Arrays.asList("pear", "grape")
49+
);
50+
System.out.println(listOfLists.get(1).get(1)); // "kiwi"
51+
System.out.println(listOfLists.stream()
52+
.flatMap(x -> x.stream()) // flatten list of lists
53+
.map(String::toUpperCase) // transform each element
54+
.toList());
55+
56+
// Example with sentences → splitting into words
57+
List<String> sentences = Arrays.asList(
58+
"Hello world",
59+
"Java streams are powerful",
60+
"flatMap is useful"
61+
);
62+
System.out.println(sentences.stream()
63+
.flatMap(sentence -> Arrays.stream(sentence.split(" "))) // split each sentence into words
64+
.map(String::toUpperCase)
65+
.toList());
66+
}
67+
}

0 commit comments

Comments
 (0)