Lesson 4 of 8
Stream Terminal Operations & Collectors
Terminal operations trigger stream evaluation and produce a result or side effect. Collectors accumulate stream elements into collections, strings, maps, or statistics. Collectors.groupingBy and Collectors.partitioningBy are especially powerful for aggregation.
Terminal Ops & Collectors
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class StreamTerminal {
public static void main(String[] args) {
List<Book> books = getCatalog();
// ── Reduction terminals ───────────────────────────────────
long count = books.stream().filter(Book::isAvailable).count();
Optional<Book> first = books.stream().findFirst();
Optional<Book> any = books.stream().parallel().findAny(); // non-deterministic
boolean anyMatch = books.stream().anyMatch(b -> b.getPrice() > 100);
boolean allMatch = books.stream().allMatch(b -> b.getPrice() > 0);
boolean noneMatch = books.stream().noneMatch(b -> b.getPrice() < 0);
Optional<Book> cheapest = books.stream()
.min(Comparator.comparingDouble(Book::getPrice));
Optional<Book> priciest = books.stream()
.max(Comparator.comparingDouble(Book::getPrice));
// reduce - fold elements into a single result
double totalValue = books.stream()
.mapToDouble(Book::getPrice)
.reduce(0.0, Double::sum); // identity + accumulator
// ── Collectors ───────────────────────────────────────────
// toList (Java 16+) - unmodifiable
List<String> titles = books.stream().map(Book::getTitle).toList();
// toList (before Java 16) - mutable
List<String> mutableTitles = books.stream()
.map(Book::getTitle)
.collect(Collectors.toList());
// joining - concatenate strings
String csv = books.stream()
.map(Book::getTitle)
.collect(Collectors.joining(", ")); // "Clean Code, Effective Java, DDIA"
String table = books.stream()
.map(b -> b.getTitle() + "=" + b.getPrice())
.collect(Collectors.joining("
", "CATALOG:
", "
=== END ==="));
// groupingBy - group into Map<K, List<V>>
Map<String, List<Book>> byAuthor = books.stream()
.collect(Collectors.groupingBy(Book::getAuthor));
// groupingBy with downstream collector
Map<String, Long> countByAuthor = books.stream()
.collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()));
Map<String, Double> avgPriceByAuthor = books.stream()
.collect(Collectors.groupingBy(
Book::getAuthor,
Collectors.averagingDouble(Book::getPrice)
));
Map<String, Optional<Book>> cheapestByAuthor = books.stream()
.collect(Collectors.groupingBy(
Book::getAuthor,
Collectors.minBy(Comparator.comparingDouble(Book::getPrice))
));
// partitioningBy - split into true/false buckets
Map<Boolean, List<Book>> partition = books.stream()
.collect(Collectors.partitioningBy(Book::isAvailable));
List<Book> available = partition.get(true);
List<Book> borrowed = partition.get(false);
// toMap - collect into Map<K,V>
Map<String, Book> byIsbn = books.stream()
.collect(Collectors.toMap(
Book::getIsbn, // key extractor
b -> b, // value extractor
(a, b) -> a // merge function (handles duplicate keys)
));
// Statistics
DoubleSummaryStatistics stats = books.stream()
.mapToDouble(Book::getPrice)
.summaryStatistics();
System.out.printf("Count=%d, Sum=%.2f, Avg=%.2f, Min=%.2f, Max=%.2f%n",
stats.getCount(), stats.getSum(), stats.getAverage(),
stats.getMin(), stats.getMax());
}
static List<Book> getCatalog() { return new ArrayList<>(); }
}Quick Quiz
Tip
Tip
Practice Stream Terminal Operations Collectors in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Stream Terminal Operations & Collectors
Practice Task
Note
Practice Task - (1) Write a working example of Stream Terminal Operations Collectors from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Stream Terminal Operations Collectors is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?