📘 Day 8: Advanced Java 8 Stream API – Terminal
Operations, Collectors & Parallel Streams
🔍 What You’ll Learn
● Terminal operations
○ forEach, collect, count, min, max, reduce, anyMatch, allMatch,
noneMatch
● Collectors
○ toList, toSet, joining, groupingBy, partitioningBy
● Parallel Streams
🔚 Terminal Operations
Terminal operations trigger the processing of the stream pipeline and produce a result.
✅ forEach()
Executes action on each element.
java
CopyEdit
[Link]("A", "B", "C").forEach([Link]::println);
✅ collect()
Transforms the stream into a collection.
java
CopyEdit
List<String> list = [Link]("Java", "Spring")
.collect([Link]());
✅ count(), min(), max()
java
CopyEdit
long count = [Link](10, 20, 30).count();
Optional<Integer> min = [Link](10, 2, 30)
.min(Integer::compareTo);
✅ reduce() – Accumulates result
java
CopyEdit
int sum = [Link](1, 2, 3, 4).reduce(0, Integer::sum); // 10
✅ Matching Operations
java
CopyEdit
boolean any = [Link]("Apple", "Banana").anyMatch(s ->
[Link]("A")); // true
boolean all = [Link]("Apple", "Apricot").allMatch(s ->
[Link]("A")); // true
boolean none = [Link]("Banana", "Berry").noneMatch(s ->
[Link]("Z")); // true
📦 Collectors API ([Link])
✅ joining()
java
CopyEdit
String result = [Link]("Rajan", "Durgesh", "Piyush")
.collect([Link](", "));
[Link](result); // Rajan, Durgesh, Piyush
✅ groupingBy()
java
CopyEdit
Map<Integer, List<String>> grouped = [Link]("Java", "Go", "Python")
.collect([Link](String::length));
✅ partitioningBy()
java
CopyEdit
Map<Boolean, List<Integer>> partition = [Link](1, 2, 3, 4, 5)
.collect([Link](n -> n % 2 == 0));
⚡ Parallel Streams
Used to process data in parallel to enhance performance (on large datasets).
java
CopyEdit
List<Integer> numbers = [Link](1, 1_000_000)
.boxed()
.collect([Link]());
long count = [Link]()
.filter(n -> n % 2 == 0)
.count();
⚠️ Parallel streams are useful for large datasets, but they can cause issues if:
● Shared mutable state exists
● You rely on order
● The data size is small (parallelism overhead)
🎤 Interview Questions – Advanced Stream API
1. What's the difference between map() and flatMap()?
● map() transforms each element into another object.
● flatMap() flattens nested structures (like List of List).
2. When would you use reduce()?
When you need to compute a single value from a stream (e.g., sum, max, min).
3. What is the use of [Link]()?
To group elements of a stream based on a classifier function (like key -> list of values).
4. What are the disadvantages of parallel streams?
Overhead of thread management, race conditions if not handled properly, and
unpredictability if order matters.
5. Can terminal operations be reused?
No, once a terminal operation is called, the stream is closed.