SyntaxPilot
Courses/Java/Lesson 38
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 38 of 51

Streams 2: collectors, grouping, Optional

queued

These are the notes for Java episode 38. At the end of the day Ravi wants to know how much money each item made. With a loop that means a HashMap filled by hand. We invent collectors: collect is the packing station at the end of a stream, and the Collectors class has ready-made packing instructions: toMap (and its duplicate key crash), groupingBy with downstream collectors like counting and summingInt, partitioningBy and joining. Then a phone lookup returns null and crashes, and we invent Optional: a box whose type says may be empty. Every example was run with javac 21.

The problem: a map filled by hand

Ravi's question: how much money did each item make? The answer isn't one number, it's a table: item → total. In Java a table like that is a Map (episode 32).

import java.util.HashMap;
import java.util.List;
import java.util.Map;
record Order(String item, int price) {}
public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("chai", 15),
                new Order("cold coffee", 60), new Order("samosa", 12),
                new Order("chai", 15));

        Map<String, Integer> totals = new HashMap<>();
        for (Order o : orders) {
            int sofar = totals.getOrDefault(o.item(), 0);
            totals.put(o.item(), sofar + o.price());
        }
        System.out.println(totals);
    }
}

Output:

{chai=45, cold coffee=60, samosa=24}

It works, but we are back to a loop and a map we keep changing by hand (getOrDefault, then put). The question was one sentence: total price, grouped by item.

collect and Collectors

Real-life example: the packing station, upgraded.

At the end of the belt In Java Meaning
The packing station collect(...) a terminal operation that packs the stream's items into a container
The packing instructions a Collector how to pack: a list, a map, a string...
Labelled baskets Collectors.groupingBy one basket per key, a Map<key, List<item>>

collect takes a Collector. You rarely write one yourself: java.util.stream.Collectors has ready-made ones such as toList(), toSet(), toMap(...), groupingBy(...), partitioningBy(...), joining(...), counting(), summingInt(...), averagingInt(...), mapping(...).

toMap, and the duplicate key crash

Collectors.toMap(keyFunction, valueFunction) builds a map: one rule for the key, one for the value.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("chai", 15));

        Map<String, Integer> totals = orders.stream()
                .collect(Collectors.toMap(Order::item, Order::price));
        System.out.println(totals);
    }
}

Output:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key chai (attempted merging values 15 and 15)
    at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:135)
    at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:182)
    at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.base/java.util.AbstractList$RandomAccessSpliterator.forEachRemaining(AbstractList.java:722)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
    at Main.main(Main.java:13)

A map holds one value per key. When the second chai arrives, toMap doesn't know whether to keep 15, replace it or add, so it throws IllegalStateException: Duplicate key. Give it a third argument, the merge function, which combines the old and the new value:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("chai", 15),
                new Order("cold coffee", 60), new Order("samosa", 12),
                new Order("chai", 15));

        Map<String, Integer> totals = orders.stream()
                .collect(Collectors.toMap(Order::item, Order::price,
                                          Integer::sum));
        System.out.println(totals);
    }
}

Output:

{chai=45, cold coffee=60, samosa=24}

Integer::sum is a method reference for (a, b) -> a + b (episode 36). Other merges: (a, b) -> a keeps the first, (a, b) -> b keeps the last, Math::max keeps the bigger one.

groupingBy: a basket per key

Collectors.groupingBy(classifier) puts each item in the basket named by the classifier, and returns Map<key, List<item>>. It creates a basket the first time it sees a key, and never complains about repeated keys: that's its whole job.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("chai", 15),
                new Order("cold coffee", 60), new Order("samosa", 12),
                new Order("chai", 15));

        Map<String, List<Order>> byItem = orders.stream()
                .collect(Collectors.groupingBy(Order::item));
        System.out.println(byItem.keySet());
        System.out.println(byItem.get("samosa"));
        System.out.println(byItem.get("chai").size() + " chai orders");
    }
}

Output:

[chai, cold coffee, samosa]
[Order[item=samosa, price=12], Order[item=samosa, price=12]]
3 chai orders

Downstream collectors: counting, summingInt and more

groupingBy(classifier, downstream) takes a second collector, the downstream collector, which decides what to do inside each basket.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
record Order(String item, int price) {}
public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("chai", 15),
                new Order("cold coffee", 60), new Order("samosa", 12),
                new Order("chai", 15));
        Map<String, Long> count = orders.stream().collect(
                Collectors.groupingBy(Order::item, Collectors.counting()));
        Map<String, Integer> money = orders.stream().collect(
                Collectors.groupingBy(Order::item,
                        Collectors.summingInt(Order::price)));
        System.out.println(count);
        System.out.println(money);
    }
}

Output:

{chai=3, cold coffee=1, samosa=2}
{chai=45, cold coffee=60, samosa=24}

counting() returns a Long, so the map is Map<String, Long>. With Map<String, Integer> the compiler refuses:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15), new Order("samosa", 12));
        Map<String, Integer> count = orders.stream().collect(
                Collectors.groupingBy(Order::item, Collectors.counting()));
        System.out.println(count);
    }
}

Output:

Main.java:10: error: incompatible types: inference variable D has incompatible equality constraints Integer,Long
        Map<String, Integer> count = orders.stream().collect(
                                                            ^
  where D,T,K,A are type-variables:
    D extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    T extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    K extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
    A extends Object declared in method <T,K,A,D>groupingBy(Function<? super T,? extends K>,Collector<? super T,A,D>)
1 error

More downstream collectors, and a three-argument groupingBy whose middle argument (TreeMap::new) chooses the map type, so the keys come out sorted:

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15), new Order("samosa", 12),
                new Order("chai", 20), new Order("cold coffee", 60), new Order("samosa", 12));

        Map<String, Double> avg = orders.stream().collect(
                Collectors.groupingBy(Order::item, TreeMap::new, Collectors.averagingInt(Order::price)));
        Map<String, List<Integer>> prices = orders.stream().collect(
                Collectors.groupingBy(Order::item, TreeMap::new,
                        Collectors.mapping(Order::price, Collectors.toList())));
        Set<String> items = orders.stream().map(Order::item).collect(Collectors.toSet());

        System.out.println(avg);
        System.out.println(prices);
        System.out.println(items.size() + " different items");
    }
}

Output:

{chai=17.5, cold coffee=60.0, samosa=12.0}
{chai=[15, 20], cold coffee=[60], samosa=[12, 12]}
3 different items
Downstream collector Gives, per basket
counting() how many items (Long)
summingInt(f) the sum of f(item) (Integer)
averagingInt(f) the average of f(item) (Double)
mapping(f, toList()) a list of f(item)
toSet() a set of the items
maxBy(comparator) the biggest item, as an Optional

partitioningBy and joining

partitioningBy(test) is a groupingBy with exactly two baskets: the map always has the keys true and false (even if a basket is empty). joining(delimiter, prefix, suffix) packs strings into one string.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> bills = List.of(45, 120, 30, 250, 80, 15);

        Map<Boolean, List<Integer>> split = bills.stream()
                .collect(Collectors.partitioningBy(b -> b >= 100));
        System.out.println("big:   " + split.get(true));
        System.out.println("small: " + split.get(false));

        String menu = List.of("chai", "samosa", "poha").stream()
                .collect(Collectors.joining(", ", "Menu: [", "]"));
        System.out.println(menu);
    }
}

Output:

big:   [120, 250]
small: [45, 30, 80, 15]
Menu: [chai, samosa, poha]

null, and why it crashes

A Map.get with a missing key returns null: "no object at all". The method's return type says String, so nothing warns the caller that the answer might be missing:

import java.util.HashMap;
import java.util.Map;

public class Main {
    static Map<String, String> phones = new HashMap<>();

    static String phoneOf(String name) {
        return phones.get(name);          // null if not found
    }

    public static void main(String[] args) {
        phones.put("Ravi", "98200 11111");
        System.out.println(phoneOf("Ravi").length());
        System.out.println(phoneOf("Asha").length());
    }
}

Output:

11
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "Main.phoneOf(String)" is null
    at Main.main(Main.java:14)

NullPointerException (NPE) is thrown when you call a method or read a field through a null reference. Since Java 14 the message (a helpful NPE message) names exactly what was null.

Optional: a box that says "may be empty"

Real-life example: a tiffin box with a label on the lid.

A tiffin box In Java Meaning
A box, lid says "may be empty" Optional<String> the type itself warns: maybe no value
Open it, lunch inside Optional[98200 11111] a value is present
Open it, it's empty: plan B Optional.empty + orElse(...) no value: use a fallback

The get() trap

Streams already return Optional: findFirst, findAny, max, min, and reduce without an identity (episode 37).

import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> menu = List.of("chai", "samosa", "poha");

        Optional<String> found = menu.stream()
                .filter(s -> s.startsWith("d"))
                .findFirst();
        System.out.println(found);
        System.out.println(found.get());
    }
}

Output:

Optional.empty
Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.base/java.util.Optional.get(Optional.java:143)
    at Main.main(Main.java:12)

get() takes the value out without checking. On an empty box that's the same crash as null, with a new name: NoSuchElementException: No value present. Avoid plain get() (its safer twin orElseThrow() at least says what it does).

The safe way

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class Main {
    static Map<String, String> phones = new HashMap<>();
    static Optional<String> phoneOf(String name) {
        return Optional.ofNullable(phones.get(name));
    }

    public static void main(String[] args) {
        phones.put("Ravi", "98200 11111");
        System.out.println(phoneOf("Ravi"));
        System.out.println(phoneOf("Asha"));
        System.out.println(phoneOf("Asha").orElse("no number"));
        System.out.println(phoneOf("Ravi").map(String::length).orElse(0));
        phoneOf("Ravi").ifPresent(p -> System.out.println("Calling " + p));
        phoneOf("Asha").ifPresent(p -> System.out.println("Calling " + p));
    }
}

Output:

Optional[98200 11111]
Optional.empty
no number
11
Calling 98200 11111
Method What it does
Optional.of(x) a full box; throws NullPointerException if x is null
Optional.ofNullable(x) full box if x isn't null, else Optional.empty()
Optional.empty() an empty box
orElse(fallback) the value, or the fallback
orElseGet(() -> ...) the value, or computes a fallback only when needed
orElseThrow() the value, or NoSuchElementException
map(f) changes the value inside, if there is one
filter(test) keeps the value only if it passes
ifPresent(action) runs the action only if a value is present
ifPresentOrElse(action, other) one of the two
isPresent() / isEmpty() true / false checks

Optional.of(null) is a mistake:

import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        String missing = null;
        System.out.println(Optional.ofNullable(missing));
        System.out.println(Optional.of(missing));
    }
}

Output:

Optional.empty
Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:233)
    at java.base/java.util.Optional.of(Optional.java:113)
    at Main.main(Main.java:7)

Optional with streams

import java.util.Comparator;
import java.util.List;
record Order(String item, int price) {}
public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15),
                new Order("samosa", 12), new Order("cold coffee", 60));
        String dearest = orders.stream()
                .max(Comparator.comparingInt(Order::price))
                .map(Order::item)
                .orElse("nothing sold");
        System.out.println(dearest);
        String none = List.<Order>of().stream()
                .max(Comparator.comparingInt(Order::price))
                .map(Order::item)
                .orElse("nothing sold");
        System.out.println(none);
    }
}

Output:

cold coffee
nothing sold

Rules of thumb: use Optional as a return type when the answer may be missing. Don't use it for fields, method parameters or collections (return an empty list instead), and never return null from a method whose return type is Optional.

Loop vs collector

Loop (how) Collector (what)
new HashMap<>(), getOrDefault, put groupingBy(Order::item, summingInt(Order::price))
easy to forget the default 0 the default is built in
the map changes step by step the map appears complete

Common mistakes (and the real error messages)

Mistake What you see Why Fix
Collectors.toMap(Order::item, Order::price) with a repeated item java.lang.IllegalStateException: Duplicate key chai (attempted merging values 15 and 15) a map holds one value per key toMap(k, v, Integer::sum) or groupingBy
Map<String, Integer> c = ... groupingBy(..., counting()) error: incompatible types: inference variable D has incompatible equality constraints Integer,Long counting() gives Long Map<String, Long>
calling a method on a null result java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "Main.phoneOf(String)" is null null is invisible in the type return Optional<String>
found.get() on an empty Optional java.util.NoSuchElementException: No value present get() doesn't check orElse, map, ifPresent
Optional.of(maybeNull) java.lang.NullPointerException of refuses null Optional.ofNullable(maybeNull)

Mini project: Ravi's end-of-day report

Items sold and money per item (sorted), the top earner (an Optional from max), big vs small orders, today's menu as one string, and the cheapest order.

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Order(String item, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("chai", 15), new Order("samosa", 12),
                new Order("chai", 15), new Order("cold coffee", 60), new Order("samosa", 12),
                new Order("chai", 15), new Order("vada pav", 20), new Order("cold coffee", 60));

        Map<String, Integer> money = orders.stream().collect(Collectors.groupingBy(
                Order::item, TreeMap::new, Collectors.summingInt(Order::price)));
        Map<String, Long> count = orders.stream().collect(Collectors.groupingBy(
                Order::item, TreeMap::new, Collectors.counting()));

        System.out.println("=== Ravi's stall: end of day ===");
        money.forEach((item, rs) ->
                System.out.println(item + ": " + count.get(item) + " sold, Rs " + rs));

        String best = money.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("nothing sold");
        System.out.println("Top earner: " + best);

        Map<Boolean, Long> big = orders.stream().collect(
                Collectors.partitioningBy(o -> o.price() >= 50, Collectors.counting()));
        System.out.println("Orders of Rs 50+: " + big.get(true) + ", smaller: " + big.get(false));

        String menu = orders.stream().map(Order::item).distinct().sorted()
                .collect(Collectors.joining(" | "));
        System.out.println("Menu today: " + menu);

        int cheapest = orders.stream().mapToInt(Order::price).min().orElse(0);
        System.out.println("Cheapest order: Rs " + cheapest);
    }
}

Output:

=== Ravi's stall: end of day ===
chai: 3 sold, Rs 45
cold coffee: 2 sold, Rs 120
samosa: 2 sold, Rs 24
vada pav: 1 sold, Rs 20
Top earner: cold coffee
Orders of Rs 50+: 2, smaller: 6
Menu today: chai | cold coffee | samosa | vada pav
Cheapest order: Rs 12

Practice

  1. Group students by city and count each city.
  2. The average marks per subject.
  3. Split the numbers 1 to 20 into even and odd.
  4. A findStudent(name) method that returns an Optional, used without ever calling get().
Solution 1
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Student(String name, String city) {}

public class Main {
    public static void main(String[] args) {
        List<Student> students = List.of(new Student("Asha", "Pune"), new Student("Ravi", "Delhi"),
                new Student("Priya", "Pune"), new Student("Neha", "Jaipur"), new Student("Arjun", "Delhi"),
                new Student("Kiran", "Pune"));
        Map<String, Long> perCity = students.stream().collect(
                Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));
        System.out.println(perCity);
    }
}

Output:

{Delhi=2, Jaipur=1, Pune=3}
Solution 2
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Mark(String subject, int marks) {}

public class Main {
    public static void main(String[] args) {
        List<Mark> marks = List.of(new Mark("Maths", 90), new Mark("Science", 72), new Mark("Maths", 70),
                new Mark("English", 85), new Mark("Science", 88), new Mark("Maths", 80));
        Map<String, Double> avg = marks.stream().collect(
                Collectors.groupingBy(Mark::subject, TreeMap::new, Collectors.averagingInt(Mark::marks)));
        System.out.println(avg);
    }
}

Output:

{English=85.0, Maths=80.0, Science=80.0}
Solution 3

IntStream has no collect(Collector), so boxed() turns it into a Stream<Integer> first.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Map<Boolean, List<Integer>> split = IntStream.rangeClosed(1, 20).boxed()
                .collect(Collectors.partitioningBy(n -> n % 2 == 0));
        System.out.println("even: " + split.get(true));
        System.out.println("odd:  " + split.get(false));
    }
}

Output:

even: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
odd:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Solution 4
import java.util.List;
import java.util.Optional;

record Student(String name, int marks) {}

public class Main {
    static List<Student> students = List.of(new Student("Asha", 91), new Student("Ravi", 78));

    static Optional<Student> findStudent(String name) {
        return students.stream().filter(s -> s.name().equals(name)).findFirst();
    }

    public static void main(String[] args) {
        System.out.println(findStudent("Asha").map(Student::marks).orElse(-1));
        System.out.println(findStudent("Neha").map(Student::marks).orElse(-1));
        findStudent("Ravi").ifPresent(s -> System.out.println("Found " + s.name()));
        System.out.println(findStudent("Neha").isPresent());
        String msg = findStudent("Neha").map(s -> "Hi " + s.name()).orElseGet(() -> "No such student");
        System.out.println(msg);
    }
}

Output:

91
-1
Found Ravi
false
No such student

Quick quiz

What does this print?

System.out.println(
    Stream.of("chai", "poha", "samosa", "chai")
        .collect(Collectors.groupingBy(
            String::length,
            Collectors.counting())));

A. {4=3, 6=1} B. {4=2, 6=1} C. {chai=2, poha=1, samosa=1} D. a duplicate key exception

Answer

A. The key is each word's length: chai, poha, chai have 4 letters (3 words) and samosa has 6 (1 word). groupingBy never throws on repeated keys.

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        System.out.println(
            Stream.of("chai", "poha", "samosa", "chai")
                .collect(Collectors.groupingBy(
                    String::length,
                    Collectors.counting())));
    }
}

Output:

{4=3, 6=1}

Interview questions

  1. What is the difference between toMap and groupingBy? toMap makes one value per key and throws IllegalStateException on a repeated key unless you pass a merge function; groupingBy collects all items with the same key into a list (or a downstream result).
  2. What is a downstream collector? The second argument of groupingBy/partitioningBy: a collector applied to the items of each group, e.g. counting(), summingInt, mapping.
  3. partitioningBy vs groupingBy? partitioningBy takes a predicate and always returns a map with exactly the keys true and false; groupingBy makes as many keys as the classifier produces.
  4. Why does Optional exist? To make "no result" visible in a method's return type, so callers must handle it, instead of getting a surprise null and a NullPointerException.
  5. orElse vs orElseGet? orElse(x) always evaluates x; orElseGet(supplier) only runs the supplier when the Optional is empty, which matters when the fallback is expensive.
  6. Optional.of vs Optional.ofNullable? of throws NullPointerException for null; ofNullable returns Optional.empty().
  7. Should you use Optional for fields or parameters? No. It's designed as a return type. For collections return an empty collection instead.
  8. Which stream operations return Optional? findFirst, findAny, max, min, reduce(op) without an identity, and on number streams max, min, average (OptionalInt, OptionalDouble).

Glossary

Term Meaning
collect a terminal operation that packs a stream's items using a Collector
Collector packing instructions for collect: what container to build and how
Collectors a class of ready-made collectors (toList, toMap, groupingBy, ...)
toMap a collector that builds a map from a key rule and a value rule
Merge function the third argument of toMap: how to combine two values for the same key
Duplicate key a key produced twice; toMap without a merge function throws IllegalStateException
groupingBy a collector that puts items into groups by a key: Map<key, List<item>>
Classifier the function that gives each item its group key, e.g. Order::item
Downstream collector a collector applied inside each group, e.g. counting(), summingInt
counting() counts the items in each group (a Long)
summingInt adds up an int value of each item in a group
averagingInt the average of an int value in each group (a Double)
mapping changes each item before passing it to another collector
partitioningBy splits items into two groups, keys true and false
joining joins strings into one, with an optional delimiter, prefix and suffix
TreeMap::new a map supplier: makes the result a TreeMap, sorted by key
null a reference that points to no object
NullPointerException thrown when a method is called (or a field read) through null
Optional<T> a container that holds one value of type T or nothing
Optional.empty() an Optional with no value
Optional.ofNullable wraps a value that may be null
orElse gets the value, or a fallback if empty
orElseGet like orElse, but computes the fallback only when needed
ifPresent runs code only when a value is present
get() takes the value out without checking; throws NoSuchElementException if empty
NoSuchElementException thrown when you ask for a value that isn't there
findFirst a terminal operation returning the first item as an Optional
boxed() turns an IntStream into a Stream<Integer>

Summary

  • collect(collector) is the terminal operation that packs a stream into a container; Collectors has the ready-made recipes.
  • toMap(key, value) throws Duplicate key on a repeated key; add a merge function like Integer::sum.
  • groupingBy(key) gives Map<key, List<item>>; add a downstream collector (counting, summingInt, averagingInt, mapping) to work inside each group, and TreeMap::new for sorted keys.
  • partitioningBy(test) gives keys true/false; joining builds one string.
  • null hides in the return type and causes NullPointerException. Optional makes "may be empty" part of the type.
  • Use orElse, orElseGet, map, ifPresent; avoid plain get(). ofNullable for values that may be null.
  • Next episode: threads: Thread, Runnable, and the life of a thread.