⚡ Java 8 Streams Programming Complete Guide

Master all method variations, downstream aggregations, primitive specializations (IntStream / DoubleStream), multi-level groupings, and interview live-coding patterns with exact real-world examples.

8+
Map Variants
12+
Collectors
100%
Runnable

🧭 Instant Decision Matrix: "Which Stream Method / Collector Should I Use?"

▼ Collapse
Target Goal Recommended Method / Collector Output Type Key Advantage
Extract single field from object stream.map(Employee::getName) Stream<String> 1-to-1 object transformation
Sum or average numeric values without boxing stream.mapToDouble(Employee::getSalary).sum() double Zero GC garbage, 5-10x faster execution
Flatten list of lists or 2D collections orders.stream().flatMap(o -> o.getItems().stream()) Stream<Item> 1-to-N flattening
Key-Value lookup with unique keys Collectors.toMap(Employee::getId, Employee::getName) Map<Integer, String> Fast $O(1)$ lookups
Key-Value lookup with possible duplicate keys Collectors.toMap(Employee::getDept, Employee::getName, (v1, v2) -> v1) Map<String, String> Prevents IllegalStateException crashes
Group entire objects by category Collectors.groupingBy(Employee::getDepartment) Map<String, List<Employee>> SQL GROUP BY equivalent
Group by category and extract only names Collectors.groupingBy(e -> e.getDept(), Collectors.mapping(e -> e.getName(), toList())) Map<String, List<String>> Extracts specific fields without post-processing
Multi-level / Nested grouping (e.g. Dept > Gender) Collectors.groupingBy(e -> e.getDept(), Collectors.groupingBy(e -> e.getGender())) Map<String, Map<String, List<T>>> Multi-dimensional categorizations
Count elements in each group Collectors.groupingBy(Employee::getDepartment, Collectors.counting()) Map<String, Long> Histogram & frequency distributions
Find highest paid person per department Collectors.groupingBy(e -> e.getDept(), Collectors.collectingAndThen(maxBy(...), Optional::get)) Map<String, Employee> Strips the messy Optional layer cleanly
Split into two binary groups (pass/fail, > threshold) Collectors.partitioningBy(e -> e.getSalary() > 90000) Map<Boolean, List<Employee>> Guaranteed to contain both true and false keys
One-pass compute count, sum, min, avg, max Collectors.summarizingDouble(Employee::getSalary) DoubleSummaryStatistics Computes 5 statistics in a single traversal
1. The `map` Family & Primitive Conversions 6 Variants
.map(Function<T, R>)
Object -> Object
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
When & Where to Use: Use whenever you want a 1-to-1 transformation of each element from type T to type R (e.g. Extracting names from Employees, converting Strings to uppercase).
List<String> names = employees.stream()
        .map(Employee::getName)
        .collect(Collectors.toList());
Output
[Alice, Bob, Charlie, Diana, Edward, Fiona, George]
.mapToInt(ToIntFunction<T>)
Primitive Specialization
IntStream mapToInt(ToIntFunction<? super T> mapper)
When & Where to Use: Use when transforming objects into primitive integers. It yields an IntStream which avoids Integer wrapper memory overhead and provides built-in statistical methods (sum(), average(), max()).
int totalIds = employees.stream()
        .mapToInt(Employee::getId)
        .sum(); // Built-in primitive sum
Output
728
.mapToDouble(ToDoubleFunction<T>)
Primitive Specialization
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
When & Where to Use: Standard choice for salary, price, financial and decimal calculations. Directly supports .sum() and .average() without creating heap objects.
double totalSalaries = employees.stream()
        .mapToDouble(Employee::getSalary)
        .sum();
Output
$655000.0
IntStream.mapToObj(IntFunction<U>)
Primitive -> Object
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)
When & Where to Use: Use when starting from an IntStream (e.g. String.chars() or IntStream.rangeClosed) and converting each primitive into a custom Object, String, or Character.
List<String> empCodes = IntStream.of(101, 102, 103)
        .mapToObj(id -> "EMP-ID-" + id)
        .collect(Collectors.toList());
Output
[EMP-ID-101, EMP-ID-102, EMP-ID-103]
IntStream.boxed()
Primitive -> Wrapper
Stream<Integer> boxed()
When & Where to Use: Fast shortcut to convert an IntStream into Stream<Integer> so that it can be collected with Collectors.toList() or Collectors.toSet().
List<Integer> nums = IntStream.rangeClosed(1, 5)
        .boxed()
        .collect(Collectors.toList());
Output
[1, 2, 3, 4, 5]
.flatMap(Function<T, Stream<R>>)
1-to-N Flattening
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
When & Where to Use: Use when each element produces a Stream or Collection itself (e.g. Employee.getSkills() returning List<String>, or lines of text into words). It flattens nested streams into one level.
List<String> allSkills = employees.stream()
        .flatMap(emp -> emp.getSkills().stream())
        .distinct()
        .sorted()
        .collect(Collectors.toList());
Output
[AWS, Accounting, Audit, Compliance, Docker, Excel, Java, Kafka, Linux, ...]
2. `Collectors.toMap`: All 3 Crucial Variants 3 Variants
toMap(keyMapper, valueMapper)
2-Arg
toMap(Function<? super T, ? extends K>, Function<? super T, ? extends U>)
When & Where to Use: Use ONLY when keys are guaranteed to be unique (e.g. Primary Key ID to Name/Object).
⚠️ CRITICAL INTERVIEW TRAP: If any duplicate key is encountered in the stream, this variant throws java.lang.IllegalStateException: Duplicate key ... and crashes!
Map<Integer, String> idToName = employees.stream()
        .collect(Collectors.toMap(
                Employee::getId,
                Employee::getName
        ));
Output
{101=Alice, 102=Bob, 103=Charlie, 104=Diana, 105=Edward, ...}
toMap(keyMapper, valueMapper, mergeFunction)
3-Arg (Safe)
toMap(keyMapper, valMapper, BinaryOperator<U> mergeFunction)
When & Where to Use: MANDATORY when keys might repeat! The mergeFunction specifies what to do when duplicate keys occur: keep old, pick new, concatenate, or take the max value.
Map<String, String> deptToNames = employees.stream()
        .collect(Collectors.toMap(
                Employee::getDepartment,
                Employee::getName,
                (oldVal, newVal) -> oldVal + " / " + newVal // Merge strategy!
        ));
Output
{Finance=Diana / Fiona, HR=Charlie / George, IT=Alice / Bob / Edward}
toMap(keyMapper, valMapper, mergeFunction, mapSupplier)
4-Arg (Custom Map)
toMap(keyMapper, valMapper, merge, Supplier<M> mapSupplier)
When & Where to Use: When you need a specific Map implementation: TreeMap::new to keep keys sorted alphabetically/numerically, or LinkedHashMap::new to preserve insertion order.
Map<String, Double> sortedDeptMaxSalary = employees.stream()
        .collect(Collectors.toMap(
                Employee::getDepartment,
                Employee::getSalary,
                Double::max,    // Keep highest salary on collision
                TreeMap::new    // Sorted keys!
        ));
Output
{Finance=125000.0, HR=70000.0, IT=115000.0}
3. `Collectors.groupingBy` & Downstream Collectors 7 Patterns
groupingBy(classifier)
Map<K, List<T>>
groupingBy(Function<? super T, ? extends K> classifier)
When & Where to Use: Standard SQL GROUP BY. Groups complete input objects into a List under each category key.
Map<String, List<Employee>> byDept = employees.stream()
        .collect(Collectors.groupingBy(Employee::getDepartment));
Output
Finance -> [Diana, Fiona], HR -> [Charlie, George], IT -> [Alice, Bob, Edward]
groupingBy(classifier, Collectors.mapping(...))
Map<K, List<String>>
groupingBy(classifier, Collectors.mapping(mapper, downstream))
When & Where to Use: When you group by a key (e.g. Department), but instead of having the entire Employee object in the list, you only want a specific attribute (e.g. only employee names or IDs).
Map<String, List<String>> namesByDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.mapping(Employee::getName, Collectors.toList())
        ));
Output
{Finance=[Diana, Fiona], HR=[Charlie, George], IT=[Alice, Bob, Edward]}
groupingBy(classifier, Collectors.counting())
Map<K, Long>
groupingBy(classifier, Collectors.counting())
When & Where to Use: Count occurrences per group (e.g. Headcount per department, character frequency in strings, word counts).
Map<String, Long> countByDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.counting()
        ));
Output
{Finance=2, HR=2, IT=3}
Nested groupingBy (Multi-Level)
Map<K1, Map<K2, List<T>>>
groupingBy(c1, groupingBy(c2))
When & Where to Use: Two-dimensional grouping (e.g. Group employees first by Department, and within each department group by Gender).
Map<String, Map<String, List<Employee>>> deptGenderMap = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.groupingBy(Employee::getGender)
        ));
Output
IT -> {Male=[Bob, Edward], Female=[Alice]}
Finance -> {Female=[Diana, Fiona]}
HR -> {Male=[Charlie, George]}
groupingBy(classifier, averagingDouble(...))
Map<K, Double>
groupingBy(classifier, Collectors.averagingDouble(ToDoubleFunction))
When & Where to Use: Calculate statistical metric per department (e.g. Average salary, total expense, average ratings).
Map<String, Double> avgSalary = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.averagingDouble(Employee::getSalary)
        ));
Output
{Finance=115000.0, HR=67500.0, IT=96666.67}
collectingAndThen(maxBy, Optional::get)
Map<K, Employee>
collectingAndThen(Collectors.maxBy(comp), Optional::get)
When & Where to Use: Collectors.maxBy() returns Optional<Employee>. By wrapping it with collectingAndThen(..., Optional::get), you unwrap the Optional so the map value is directly Employee.
Map<String, Employee> topPaidPerDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.collectingAndThen(
                        Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)),
                        Optional::get
                )
        ));
Output
Finance -> Fiona ($125,000)
HR -> George ($70,000)
IT -> Bob ($115,000)
groupingBy(classifier, mapFactory, downstream)
TreeMap Sorted Keys
groupingBy(classifier, Supplier<M>, downstream)
When & Where to Use: When you need the grouping result keys to be automatically sorted alphabetically (via TreeMap::new) or maintain insertion order (via LinkedHashMap::new).
Map<String, Long> sortedDeptCounts = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                TreeMap::new,           // Sort keys naturally
                Collectors.counting()
        ));
Output
{Finance=2, HR=2, IT=3} (Always in alphabetical key order)
4. Partitioning, Joining & Reductions 5 Methods
Collectors.partitioningBy(Predicate)
Map<Boolean, List<T>>
partitioningBy(Predicate<? super T> predicate)
When & Where to Use: Special case of grouping that splits data strictly into two buckets: true and false. Both keys will always exist in the map, even if empty.
Map<Boolean, List<Employee>> salarySplit = employees.stream()
        .collect(Collectors.partitioningBy(e -> e.getSalary() > 90000));

List<Employee> highEarners = salarySplit.get(true);
List<Employee> normalEarners = salarySplit.get(false);
Output
true (High) -> [Alice, Bob, Diana, Fiona]
false (Normal) -> [Charlie, Edward, George]
Collectors.joining(delim, prefix, suffix)
String Joining
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
When & Where to Use: Concatenate string elements with clean formatting without trailing commas.
// 3 Variants:
// 1. joining() -> "AliceBobCharlie"
// 2. joining(", ") -> "Alice, Bob, Charlie"
// 3. joining(", ", "[Prefix: ", "]")
String result = employees.stream()
        .map(Employee::getName)
        .collect(Collectors.joining(", ", "[Staff: ", "]"));
Output
[Staff: Alice, Bob, Charlie, Diana, Edward, Fiona, George]
Collectors.summarizingDouble(...)
One-Pass 5 Stats
summarizingDouble(ToDoubleFunction<? super T> mapper)
When & Where to Use: When you need count, sum, minimum, average, and maximum simultaneously without looping multiple times over the stream.
DoubleSummaryStatistics stats = employees.stream()
        .collect(Collectors.summarizingDouble(Employee::getSalary));

System.out.printf("Count:%d, Sum:%.2f, Min:%.2f, Avg:%.2f, Max:%.2f",
        stats.getCount(), stats.getSum(), stats.getMin(), 
        stats.getAverage(), stats.getMax());
Output
Count:7, Sum:655000.00, Min:65000.00, Avg:93571.43, Max:125000.00
.reduce(identity, accumulator)
Custom Reduction
T reduce(T identity, BinaryOperator<T> accumulator)
When & Where to Use: General purpose folding / aggregation (e.g. Finding longest string, computing custom products or rolling balances).
Optional<String> longestName = employees.stream()
        .map(Employee::getName)
        .reduce((s1, s2) -> s1.length() >= s2.length() ? s1 : s2);
Output
"Charlie"
distinct().sorted().skip(1).findFirst()
N-th Highest Pattern
Stream Slicing: distinct() + sorted(rev) + skip(N-1)
When & Where to Use: Standard formula in every tech interview to find the 2nd highest salary, 3rd highest number, etc.
Optional<Double> secondHighestSalary = employees.stream()
        .map(Employee::getSalary)
        .distinct()                           // Eliminate duplicate salaries
        .sorted(Comparator.reverseOrder())    // Descending order
        .skip(1)                              // Skip highest
        .findFirst();
Output
Optional[115000.0]

Want to run and test these in your terminal?

All examples above are compiled and verified inside java8/StreamMasterclassGuide.java.

javac -d bin java8/StreamMasterclassGuide.java && java -cp bin java8.StreamMasterclassGuide