Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 09 / Stage 2

Generics, collections and functional Java

Goal: Write your own generic classes and methods, implement Comparable and write a Comparator, choose the right List/Set/Map/Deque implementation for the job, then use lambdas, method references, the Streams API and Optional the way idiomatic Java actually looks. Time: ~8 hours

What you will learn

  • Why generics exist: the casting problem they remove, and what "type erasure" means
  • Writing your own generic class (Box<T>, Pair<K, V>) and a generic method
  • Bounded type parameters (<T extends Comparable<T>>) and a first look at wildcards
  • Comparable (a class's own natural order) vs. Comparator (any order you want, from outside)
  • Choosing between ArrayList/LinkedList, HashSet/LinkedHashSet/TreeSet, HashMap/LinkedHashMap/TreeMap, and Deque as a stack or queue
  • Java 21's sequenced collections: getFirst(), getLast(), reversed() on one API
  • Lambdas and the built-in functional interfaces: Predicate, Function, Supplier, Consumer, BiFunction, UnaryOperator
  • The four kinds of method references
  • The Streams API: filter/map/sorted, collecting with Collectors, and why streams are lazy
  • Optional: saying "this might be missing" in the type, instead of returning null

Topics in this part

Practice

Write each answer in its own file with a public static void main(String[] args) method, just like the README's examples. Where an exercise says "print", match the sample output exactly, including spacing and capitalisation.


Exercise 1: A generic storage unit

Scenario: A packers-and-movers warehouse wants one storage unit class that works for labels, parcels, or anything else, with a fixed capacity. What to do: Write a generic class StorageUnit<T> with a constructor StorageUnit(int capacity), and methods store(T item) (returns false instead of storing once full), retrieve(int index), isEmpty() and size(). Then in main:

  1. Make a StorageUnit<String> with capacity 2. Print isEmpty() before storing anything.
  2. Store "Fragile", then "Keep dry", then try to store "Heavy" (over capacity) — print the boolean each store(...) call returns.
  3. Print the size and retrieve(0).
  4. Make a record Parcel(String trackingId, double weightKg), create a StorageUnit<Parcel> with capacity 5, store two Parcels, and print its size and retrieve(0).
  5. Print both units' getClass().getSimpleName(), and whether the two units have the same runtime class.

Sample output:

empty before storing: true
store 'Fragile': true
store 'Keep dry': true
store 'Heavy' (over capacity): false
size: 2, retrieve(0): Fragile
parcel unit size: 2
first parcel: Parcel[trackingId=TRK-001, weightKg=4.5]
labelUnit runtime class: StorageUnit
parcelUnit runtime class: StorageUnit
same runtime class (erasure): true

💡 Hint: store should check items.size() >= capacity before adding. The last line is true because of type erasure (section 2): both units are the same StorageUnit class at run time, whatever T was at compile time.


Exercise 2: A bounded generic method, smallestOf

Scenario: A delivery app needs "which of these is the smallest?" to work for weights, names and ratings, without writing it three times. What to do: Write static <T extends Comparable<? super T>> T smallestOf(Collection<T> items), the mirror image of the README's max. Then print:

  1. The lightest of List.of(12, 4, 9, 2, 15) (kilograms).
  2. The alphabetically-first of List.of("Ravi", "Asha", "Kabir", "Meera").
  3. The lowest of List.of(4.5, 3.2, 4.8, 2.9).

Sample output:

lightest delivery: 2 kg
first driver alphabetically: Asha
lowest rating: 2.9

💡 Hint: Use an Iterator<T>, take the first element as the running "smallest", then compare the rest with compareTo, flipping the README's > 0 to < 0.


Exercise 3: Employees, natural order and two Comparators

Scenario: An HR system has employees with an ID, a name, a performance score and a salary, and needs three different sort orders without changing the Employee class each time. What to do: Write Employee implements Comparable<Employee> with fields id, name, performanceScore, salary, whose natural order (compareTo) sorts by id. Then, given the four employees below, print, one per line, each list sorted by:

  1. Natural order (list.sort(null)).
  2. Performance score descending, then name ascending as a tie-breaker.
  3. Salary descending.

Starting data:

new Employee("E-03", "Kabir", 88, 72000);
new Employee("E-01", "Asha", 95, 85000);
new Employee("E-04", "Meera", 88, 79000);
new Employee("E-02", "Ravi", 72, 60000);

Sample output:

== natural order (by id) ==
E-01 Asha score=95 salary=Rs.85000.0
E-02 Ravi score=72 salary=Rs.60000.0
E-03 Kabir score=88 salary=Rs.72000.0
E-04 Meera score=88 salary=Rs.79000.0

== by performance score (desc), then name (asc) ==
E-01 Asha score=95 salary=Rs.85000.0
E-03 Kabir score=88 salary=Rs.72000.0
E-04 Meera score=88 salary=Rs.79000.0
E-02 Ravi score=72 salary=Rs.60000.0

== by salary (desc) ==
E-01 Asha score=95 salary=Rs.85000.0
E-04 Meera score=88 salary=Rs.79000.0
E-03 Kabir score=88 salary=Rs.72000.0
E-02 Ravi score=72 salary=Rs.60000.0

💡 Hint: Comparator.comparingInt((Employee e) -> e.performanceScore).reversed().thenComparing(e -> e.name) — the cast on the lambda parameter is needed so the compiler knows which overload of comparingInt you mean before it has seen the rest of the chain.


Exercise 4: Four scenarios, four collection choices

Scenario: A city-trip app needs four different "keep track of things" behaviours, and picking the right collection is the whole exercise. What to do: For each scenario, pick the right implementation from section 5 and print the result:

  1. Deduplicate {"411001", "110001", "411001", "600001", "110001", "560001"} while keeping the order each PIN code was first seen.
  2. A leaderboard (score -> name) that must always be read out lowest score to highest; also print the entry with the top score.
  3. An undo stack: push "type 'Hello'", "type ' World'", "delete last word", then undo (pop) twice, printing what was undone each time, and the remaining history.
  4. A print queue: offer "invoice.pdf", "report.pdf", "label.pdf", then print (poll) twice, printing what printed each time, and what is still queued.

Sample output:

unique pin codes, first-seen order: [411001, 110001, 600001, 560001]
leaderboard, lowest to highest score: {760=Meera, 980=Asha, 1200=Ravi}
top score entry: 1200=Ravi
undo: delete last word
undo: type ' World'
remaining history: [type 'Hello']
printing: invoice.pdf
printing: report.pdf
still queued: [label.pdf]

💡 Hint: 1 is a LinkedHashSet, 2 is a TreeMap, 3 and 4 are both an ArrayDeque — 3 uses push/pop, 4 uses offer/poll.


Exercise 5: Loan eligibility with composed Predicates

Scenario: A micro-lending app checks two rules — enough income, good credit score — and needs three different groups from the same two rules, plus an EMI estimate. What to do: Given record Applicant(String name, double monthlyIncome, int creditScore), write two Predicate<Applicant>: minIncome (income >= 30000) and goodCredit (score >= 700). Using only .and()/.negate() on these two (no new lambdas), print, one name per line:

  1. Eligible: minIncome AND goodCredit.
  2. Needs manual review: enough income, but not good credit.
  3. Rejected: not eligible, and not under review either.

Then write Function<Double, Double> estimateEmi by composing a "loan amount = income × 10" step with a "monthly EMI = amount ÷ 36" step using .andThen(...), and print each applicant's estimated EMI as Rs. %.2f.

Starting data:

new Applicant("Asha", 65000, 760);
new Applicant("Ravi", 28000, 710);
new Applicant("Meera", 90000, 610);
new Applicant("Kabir", 32000, 580);

Sample output:

== eligible (income >= 30,000 AND credit score >= 700) ==
Asha

== needs manual review (enough income, weak credit) ==
Meera
Kabir

== rejected (not eligible AND not under review) ==
Ravi

== Function: a simple EMI estimate, composed from two steps ==
Asha   estimated EMI: Rs. 18055.56
Ravi   estimated EMI: Rs. 7777.78
Meera  estimated EMI: Rs. 25000.00
Kabir  estimated EMI: Rs. 8888.89

💡 Hint: "needs review" is minIncome.and(goodCredit.negate()); "rejected" is the negation of both eligible and needsReview, combined with .and(...).


Exercise 6: A stationery shop's inventory report

Scenario: A stationery shop wants a short report over its inventory: value by category, which items are running low, and the average price per category. What to do: Given record Item(String name, String category, int stock, double unitPrice) and stockValue() = stock * unitPrice, print:

  1. Total stock value by category, as a Map sorted by category name, formatted Rs. %.2f.
  2. Names of items with stock < 10, alphabetically.
  3. Every item's name, comma-joined, alphabetically.
  4. Average unit price by category, sorted by category name, formatted Rs. %.2f.

Starting data:

new Item("Notebook", "Stationery", 120, 45.0);
new Item("Pen", "Stationery", 8, 8.0);
new Item("Stapler", "Stationery", 15, 90.0);
new Item("USB Cable", "Electronics", 60, 150.0);
new Item("Mouse", "Electronics", 4, 450.0);

Sample output:

== total stock value by category, sorted by category name ==
  Electronics  Rs. 10800.00
  Stationery   Rs. 6814.00

== low-stock items (stock < 10), names only, alphabetical ==
[Mouse, Pen]

== item names, comma-joined ==
Mouse, Notebook, Pen, Stapler, USB Cable

== average unit price per category ==
  Electronics  Rs. 300.00
  Stationery   Rs. 47.67

💡 Hint: Collectors.groupingBy(Item::category, TreeMap::new, Collectors.summingDouble(Item::stockValue)) for part 1; Collectors.averagingDouble(Item::unitPrice) for part 4.


Exercise 7: Optional, flatMap and a manager lookup

Scenario: An HR directory has employees with an optional manager ID, and some of that data is broken — a manager ID that points nowhere. What to do: Given record Employee(String id, String name, String managerId) (where managerId may be null), write findById(String id) returning Optional<Employee>, and managerOf(Employee e) returning Optional<Employee> (empty if e.managerId() is null, otherwise the result of findById on it — which can also be empty, if the ID is bad data). Using the data below:

  1. Print whether "E-01" and "E-77" are found by findById.
  2. For each of "E-01", "E-02", "E-03", "E-77", look the employee up, flatMap to their manager, map to the manager's name, and print <id> -> <manager name or "no manager on record">.
  3. Look up "E-02", .filter to confirm managerId() == null, and orElseThrow your own IllegalStateException if that is somehow not true; print the confirmed name. Then do the same .filter on "E-01" (which does have a manager) inside a try/catch, and print the caught message.

Starting data:

new Employee("E-01", "Asha", "E-02");
new Employee("E-02", "Ravi", null);     // Ravi has no manager: he is the top
new Employee("E-03", "Meera", "E-99");  // E-99 does not exist: bad data

Sample output:

== direct lookup ==
E-01 found: true
E-77 found: false

== manager name via flatMap, with a fallback for every case ==
E-01 -> Ravi
E-02 -> no manager on record
E-03 -> no manager on record
E-77 -> no manager on record

== filter + orElseThrow: enforce a rule, fail loudly if it's broken ==
confirmed top manager: Ravi
caught: E-01 was expected to have no manager, but has one

💡 Hint: E-03's manager ID "E-99" does not exist, so findById("E-99") inside managerOf is itself empty — flatMap on an empty result from either step stays empty, which is why E-03 prints the same fallback as a truly missing employee.


Exercise 8: A library catalog, all of Part 9 combined

Scenario: A library wants one small report that ranks books, breaks them down by genre, flags what is out of stock, and recommends the best book that is actually on the shelf — exactly the kind of report real code builds by combining a generic repository, Comparator, streams and Optional. What to do: Reuse (or rewrite) the README's generic Repository<T> (all() and findFirst(Predicate<T>)). Given record Book(String isbn, String title, String genre, double rating, int copiesAvailable) and the data below, print:

  1. All books ranked by rating descending, then title ascending, as <rating> <title padded to 16> (<genre>).
  2. Average rating by genre, sorted by genre name, as <genre padded to 12> <avg to 2 decimals>.
  3. Titles of books with copiesAvailable == 0.
  4. The title found via Repository.findFirst for ISBN "978-0-03", and the fallback "not in catalog" for "978-0-99".
  5. The single highest-rated "Technology" book with copiesAvailable > 0 (via .max(Comparator...) on the stream), printed as recommend: <title> (<n> copies left), or a clear message if none qualify.

Starting data:

new Book("978-0-01", "The Alchemist", "Fiction", 4.4, 3);
new Book("978-0-02", "Clean Code", "Technology", 4.6, 0);
new Book("978-0-03", "Sapiens", "Non-fiction", 4.7, 2);
new Book("978-0-04", "Wings of Fire", "Non-fiction", 4.8, 5);
new Book("978-0-05", "Effective Java", "Technology", 4.6, 1);

Sample output:

== 1. Books ranked by rating (desc), then title (asc) as a tie-breaker ==
  4.8  Wings of Fire    (Non-fiction)
  4.7  Sapiens          (Non-fiction)
  4.6  Clean Code       (Technology)
  4.6  Effective Java   (Technology)
  4.4  The Alchemist    (Fiction)

== 2. Average rating by genre, sorted by genre name ==
  Fiction      4.40
  Non-fiction  4.75
  Technology   4.60

== 3. Books currently out of stock ==
[Clean Code]

== 4. Optional: safe lookup by ISBN, with a fallback message ==
978-0-03 -> Sapiens
978-0-99 -> not in catalog

== 5. The single best Technology book that is IN STOCK, or a clear message ==
recommend: Effective Java (1 copies left)

💡 Hint: For part 1, Comparator.comparingDouble(Book::rating).reversed().thenComparing(Book::title) — reversed() only flips the part of the comparator chain built so far, so it must come right after the field you want descending, before thenComparing adds the tie-breaker. For part 5, Clean Code is excluded even though it ties on rating, because its copiesAvailable is 0 and the stream is filtered before .max(...) runs.

Show the solutions for Part 9 (8 files)

solutions/ex01.java

import java.util.ArrayList;
import java.util.List;

class Ex01 {

    static class StorageUnit<T> {
        private final List<T> items = new ArrayList<>();
        private final int capacity;

        StorageUnit(int capacity) {
            this.capacity = capacity;
        }

        boolean store(T item) {
            if (items.size() >= capacity) {
                return false;
            }
            items.add(item);
            return true;
        }

        T retrieve(int index) {
            return items.get(index);
        }

        boolean isEmpty() {
            return items.isEmpty();
        }

        int size() {
            return items.size();
        }
    }

    record Parcel(String trackingId, double weightKg) {
    }

    public static void main(String[] args) {
        StorageUnit<String> labelUnit = new StorageUnit<>(2);
        System.out.println("empty before storing: " + labelUnit.isEmpty());
        System.out.println("store 'Fragile': " + labelUnit.store("Fragile"));
        System.out.println("store 'Keep dry': " + labelUnit.store("Keep dry"));
        System.out.println("store 'Heavy' (over capacity): " + labelUnit.store("Heavy"));
        System.out.println("size: " + labelUnit.size() + ", retrieve(0): " + labelUnit.retrieve(0));

        StorageUnit<Parcel> parcelUnit = new StorageUnit<>(5);
        parcelUnit.store(new Parcel("TRK-001", 4.5));
        parcelUnit.store(new Parcel("TRK-002", 1.2));
        System.out.println("parcel unit size: " + parcelUnit.size());
        System.out.println("first parcel: " + parcelUnit.retrieve(0));

        System.out.println("labelUnit runtime class: " + labelUnit.getClass().getSimpleName());
        System.out.println("parcelUnit runtime class: " + parcelUnit.getClass().getSimpleName());
        System.out.println("same runtime class (erasure): " + (labelUnit.getClass() == parcelUnit.getClass()));
    }
}

solutions/ex02.java

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

class Ex02 {

    // Bounded generic method: T must be Comparable to itself (or a supertype).
    static <T extends Comparable<? super T>> T smallestOf(Collection<T> items) {
        Iterator<T> it = items.iterator();
        T smallest = it.next();
        while (it.hasNext()) {
            T next = it.next();
            if (next.compareTo(smallest) < 0) {
                smallest = next;
            }
        }
        return smallest;
    }

    public static void main(String[] args) {
        List<Integer> deliveryWeightsKg = List.of(12, 4, 9, 2, 15);
        List<String> driverNames = List.of("Ravi", "Asha", "Kabir", "Meera");

        System.out.println("lightest delivery: " + smallestOf(deliveryWeightsKg) + " kg");
        System.out.println("first driver alphabetically: " + smallestOf(driverNames));

        List<Double> ratings = List.of(4.5, 3.2, 4.8, 2.9);
        System.out.println("lowest rating: " + smallestOf(ratings));
    }
}

solutions/ex03.java

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class Ex03 {

    static class Employee implements Comparable<Employee> {
        final String id;
        final String name;
        final int performanceScore;
        final double salary;

        Employee(String id, String name, int performanceScore, double salary) {
            this.id = id;
            this.name = name;
            this.performanceScore = performanceScore;
            this.salary = salary;
        }

        @Override
        public int compareTo(Employee other) {
            return this.id.compareTo(other.id); // natural order: by employee id
        }

        @Override
        public String toString() {
            return id + " " + name + " score=" + performanceScore + " salary=Rs." + salary;
        }
    }

    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>(List.of(
                new Employee("E-03", "Kabir", 88, 72000),
                new Employee("E-01", "Asha", 95, 85000),
                new Employee("E-04", "Meera", 88, 79000),
                new Employee("E-02", "Ravi", 72, 60000)
        ));

        System.out.println("== natural order (by id) ==");
        List<Employee> byId = new ArrayList<>(employees);
        byId.sort(null);
        byId.forEach(System.out::println);

        System.out.println();
        System.out.println("== by performance score (desc), then name (asc) ==");
        Comparator<Employee> byScoreThenName = Comparator
                .comparingInt((Employee e) -> e.performanceScore).reversed()
                .thenComparing(e -> e.name);
        List<Employee> ranked = new ArrayList<>(employees);
        ranked.sort(byScoreThenName);
        ranked.forEach(System.out::println);

        System.out.println();
        System.out.println("== by salary (desc) ==");
        List<Employee> bySalary = new ArrayList<>(employees);
        bySalary.sort(Comparator.comparingDouble((Employee e) -> e.salary).reversed());
        bySalary.forEach(System.out::println);
    }
}

solutions/ex04.java

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeMap;

class Ex04 {

    public static void main(String[] args) {
        // 1. Unique pin codes visited, keeping the order they were first seen in -> LinkedHashSet.
        String[] visitedPins = {"411001", "110001", "411001", "600001", "110001", "560001"};
        Set<String> uniquePinsInOrder = new LinkedHashSet<>();
        for (String pin : visitedPins) {
            uniquePinsInOrder.add(pin);
        }
        System.out.println("unique pin codes, first-seen order: " + uniquePinsInOrder);

        // 2. A leaderboard that must always print sorted by score -> TreeMap.
        TreeMap<Integer, String> leaderboard = new TreeMap<>();
        leaderboard.put(980, "Asha");
        leaderboard.put(1200, "Ravi");
        leaderboard.put(760, "Meera");
        System.out.println("leaderboard, lowest to highest score: " + leaderboard);
        System.out.println("top score entry: " + leaderboard.lastEntry());

        // 3. Undo history for a text editor: last action undone first -> Deque as a stack.
        Deque<String> undoStack = new ArrayDeque<>();
        undoStack.push("type 'Hello'");
        undoStack.push("type ' World'");
        undoStack.push("delete last word");
        System.out.println("undo: " + undoStack.pop());
        System.out.println("undo: " + undoStack.pop());
        System.out.println("remaining history: " + undoStack);

        // 4. A print queue: first job in, first job printed -> Deque as a queue.
        Deque<String> printQueue = new ArrayDeque<>();
        printQueue.offer("invoice.pdf");
        printQueue.offer("report.pdf");
        printQueue.offer("label.pdf");
        System.out.println("printing: " + printQueue.poll());
        System.out.println("printing: " + printQueue.poll());
        System.out.println("still queued: " + printQueue);
    }
}

solutions/ex05.java

import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

class Ex05 {

    record Applicant(String name, double monthlyIncome, int creditScore) {
    }

    public static void main(String[] args) {
        List<Applicant> applicants = List.of(
                new Applicant("Asha", 65000, 760),
                new Applicant("Ravi", 28000, 710),
                new Applicant("Meera", 90000, 610),
                new Applicant("Kabir", 32000, 580)
        );

        Predicate<Applicant> minIncome = a -> a.monthlyIncome() >= 30000;
        Predicate<Applicant> goodCredit = a -> a.creditScore() >= 700;
        Predicate<Applicant> eligible = minIncome.and(goodCredit);
        Predicate<Applicant> needsReview = minIncome.and(goodCredit.negate());

        System.out.println("== eligible (income >= 30,000 AND credit score >= 700) ==");
        applicants.stream().filter(eligible).map(Applicant::name).forEach(System.out::println);

        System.out.println();
        System.out.println("== needs manual review (enough income, weak credit) ==");
        applicants.stream().filter(needsReview).map(Applicant::name).forEach(System.out::println);

        System.out.println();
        System.out.println("== rejected (not eligible AND not under review) ==");
        applicants.stream().filter(eligible.negate().and(needsReview.negate())).map(Applicant::name).forEach(System.out::println);

        System.out.println();
        System.out.println("== Function: a simple EMI estimate, composed from two steps ==");
        Function<Double, Double> loanAmount = income -> income * 10; // up to 10x monthly income
        Function<Double, Double> monthlyEmi = amount -> amount / 36; // spread over 36 months
        Function<Double, Double> estimateEmi = loanAmount.andThen(monthlyEmi);
        for (Applicant a : applicants) {
            System.out.printf("%-6s estimated EMI: Rs. %.2f%n", a.name(), estimateEmi.apply(a.monthlyIncome()));
        }
    }
}

solutions/ex06.java

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

class Ex06 {

    record Item(String name, String category, int stock, double unitPrice) {
        double stockValue() {
            return stock * unitPrice;
        }
    }

    public static void main(String[] args) {
        List<Item> inventory = List.of(
                new Item("Notebook", "Stationery", 120, 45.0),
                new Item("Pen", "Stationery", 8, 8.0),
                new Item("Stapler", "Stationery", 15, 90.0),
                new Item("USB Cable", "Electronics", 60, 150.0),
                new Item("Mouse", "Electronics", 4, 450.0)
        );

        System.out.println("== total stock value by category, sorted by category name ==");
        Map<String, Double> valueByCategory = inventory.stream()
                .collect(Collectors.groupingBy(Item::category, TreeMap::new, Collectors.summingDouble(Item::stockValue)));
        valueByCategory.forEach((category, value) -> System.out.printf("  %-12s Rs. %.2f%n", category, value));

        System.out.println();
        System.out.println("== low-stock items (stock < 10), names only, alphabetical ==");
        List<String> lowStock = inventory.stream()
                .filter(item -> item.stock() < 10)
                .map(Item::name)
                .sorted()
                .toList();
        System.out.println(lowStock);

        System.out.println();
        System.out.println("== item names, comma-joined ==");
        String catalog = inventory.stream().map(Item::name).sorted().collect(Collectors.joining(", "));
        System.out.println(catalog);

        System.out.println();
        System.out.println("== average unit price per category ==");
        Map<String, Double> avgPriceByCategory = inventory.stream()
                .collect(Collectors.groupingBy(Item::category, TreeMap::new, Collectors.averagingDouble(Item::unitPrice)));
        avgPriceByCategory.forEach((category, avg) -> System.out.printf("  %-12s Rs. %.2f%n", category, avg));
    }
}

solutions/ex07.java

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

class Ex07 {

    record Employee(String id, String name, String managerId) {
    }

    static final List<Employee> EMPLOYEES = List.of(
            new Employee("E-01", "Asha", "E-02"),
            new Employee("E-02", "Ravi", null),       // Ravi has no manager: he is the top
            new Employee("E-03", "Meera", "E-99")      // E-99 does not exist (bad data)
    );

    static Optional<Employee> findById(String id) {
        return EMPLOYEES.stream().filter(e -> e.id().equals(id)).findFirst();
    }

    static Optional<Employee> managerOf(Employee employee) {
        if (employee.managerId() == null) {
            return Optional.empty();
        }
        return findById(employee.managerId());
    }

    public static void main(String[] args) {
        System.out.println("== direct lookup ==");
        System.out.println("E-01 found: " + findById("E-01").isPresent());
        System.out.println("E-77 found: " + findById("E-77").isPresent());

        System.out.println();
        System.out.println("== manager name via flatMap, with a fallback for every case ==");
        for (String id : List.of("E-01", "E-02", "E-03", "E-77")) {
            String managerName = findById(id)
                    .flatMap(Ex07::managerOf)
                    .map(Employee::name)
                    .orElse("no manager on record");
            System.out.println(id + " -> " + managerName);
        }

        System.out.println();
        System.out.println("== filter + orElseThrow: enforce a rule, fail loudly if it's broken ==");
        try {
            Employee topManager = findById("E-02")
                    .filter(e -> e.managerId() == null)
                    .orElseThrow(() -> new IllegalStateException("E-02 was expected to have no manager"));
            System.out.println("confirmed top manager: " + topManager.name());

            findById("E-01")
                    .filter(e -> e.managerId() == null)
                    .orElseThrow(() -> new IllegalStateException("E-01 was expected to have no manager, but has one"));
        } catch (IllegalStateException e) {
            System.out.println("caught: " + e.getMessage());
        }
    }
}

solutions/ex08.java

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;

class Ex08 {

    record Book(String isbn, String title, String genre, double rating, int copiesAvailable) {
    }

    // A small generic repository, reused for Book here, for anything else later.
    static class Repository<T> {
        private final List<T> items;

        Repository(List<T> items) {
            this.items = items;
        }

        List<T> all() {
            return items;
        }

        Optional<T> findFirst(Predicate<T> match) {
            return items.stream().filter(match).findFirst();
        }
    }

    public static void main(String[] args) {
        Repository<Book> catalog = new Repository<>(List.of(
                new Book("978-0-01", "The Alchemist", "Fiction", 4.4, 3),
                new Book("978-0-02", "Clean Code", "Technology", 4.6, 0),
                new Book("978-0-03", "Sapiens", "Non-fiction", 4.7, 2),
                new Book("978-0-04", "Wings of Fire", "Non-fiction", 4.8, 5),
                new Book("978-0-05", "Effective Java", "Technology", 4.6, 1)
        ));

        System.out.println("== 1. Books ranked by rating (desc), then title (asc) as a tie-breaker ==");
        List<Book> ranked = catalog.all().stream()
                .sorted(Comparator.comparingDouble(Book::rating).reversed().thenComparing(Book::title))
                .toList();
        ranked.forEach(b -> System.out.printf("  %.1f  %-16s (%s)%n", b.rating(), b.title(), b.genre()));

        System.out.println();
        System.out.println("== 2. Average rating by genre, sorted by genre name ==");
        Map<String, Double> avgRatingByGenre = catalog.all().stream()
                .collect(Collectors.groupingBy(Book::genre, TreeMap::new, Collectors.averagingDouble(Book::rating)));
        avgRatingByGenre.forEach((genre, avg) -> System.out.printf("  %-12s %.2f%n", genre, avg));

        System.out.println();
        System.out.println("== 3. Books currently out of stock ==");
        List<String> outOfStock = catalog.all().stream()
                .filter(b -> b.copiesAvailable() == 0)
                .map(Book::title)
                .toList();
        System.out.println(outOfStock);

        System.out.println();
        System.out.println("== 4. Optional: safe lookup by ISBN, with a fallback message ==");
        String found = catalog.findFirst(b -> b.isbn().equals("978-0-03")).map(Book::title).orElse("not in catalog");
        String missing = catalog.findFirst(b -> b.isbn().equals("978-0-99")).map(Book::title).orElse("not in catalog");
        System.out.println("978-0-03 -> " + found);
        System.out.println("978-0-99 -> " + missing);

        System.out.println();
        System.out.println("== 5. The single best Technology book that is IN STOCK, or a clear message ==");
        Optional<Book> bestAvailableTech = catalog.all().stream()
                .filter(b -> b.genre().equals("Technology") && b.copiesAvailable() > 0)
                .max(Comparator.comparingDouble(Book::rating));
        bestAvailableTech.ifPresentOrElse(
                b -> System.out.println("recommend: " + b.title() + " (" + b.copiesAvailable() + " copies left)"),
                () -> System.out.println("no Technology book is in stock right now"));
    }
}

Common mistakes

Mistake Why it is wrong Fix
new T() or new T[10] inside a generic class Type erasure removes T at run time; there is nothing left to construct Pass a Supplier<T>/a Class<T>, or use List<T> instead of an array
<T> with no bound, then calling compareTo/a specific method on it Plain T only has the methods every Object has <T extends Comparable<? super T>> or whatever interface you actually need
@Override public int compareTo(...) that is not consistent with equals Sorted collections and equals-based ones can disagree about what is "the same" Make compareTo return 0 exactly when equals returns true, where practical
Choosing HashSet/HashMap and then printing/relying on their iteration order That order is not defined and can change between runs or JDK versions Use LinkedHashSet/LinkedHashMap (insertion order) or TreeSet/TreeMap (sorted) if order matters
A lambda with a body that does nothing but call one existing method Harder to read than it needs to be A method reference: x -> x.toUpperCase() → String::toUpperCase
Calling .get() on an Optional without checking first Throws NoSuchElementException if it is empty — exactly the crash Optional exists to prevent .orElse(...), .orElseThrow(...), or .ifPresentOrElse(...)
optional.orElse(buildExpensiveDefault()) orElse's argument is always built, even when the Optional is present orElseGet(() -> buildExpensiveDefault()) — only called when actually needed
Calling .peek() to do real work in a stream pipeline Whether a peek step runs on every element depends on the rest of the pipeline (short-circuiting, count()) Use .forEach(...) as the terminal operation for side effects
Using a stream twice (stream.count(); stream.toList();) A stream can only be consumed once; the second call throws IllegalStateException Build a fresh stream from the source each time, or collect to a List first

Quick recap

  • Generics let the compiler check a container's contents at every use; type erasure means that type information is gone by run time.
  • A bounded type parameter (<T extends Comparable<T>>) lets a generic method call methods that plain Object does not have.
  • Comparable is one, permanent order defined by the class; Comparator is any order, defined from outside, and composes with .reversed()/.thenComparing(...).
  • Pick a collection by the order guarantee you need: ArrayList/HashSet/HashMap (no order promise, fastest), LinkedHashSet/LinkedHashMap (insertion order), TreeSet/TreeMap (sorted), ArrayDeque (stack or queue).
  • Predicate, Function, Supplier, Consumer, BiFunction and UnaryOperator cover almost every lambda you will write; compose them with .and()/.or()/.negate()/.andThen()/.compose() instead of writing bigger lambdas.
  • A method reference (::) replaces a lambda whose whole body is "call one existing method," in four shapes: static, bound instance, unbound instance, constructor.
  • A stream is intermediate operations (lazy, build a plan) followed by exactly one terminal operation (actually runs the plan); Collectors.groupingBy/partitioningBy/joining cover most real reports.
  • Optional<T> says "might be missing" in the type; chain map/filter/flatMap, then resolve with orElse/orElseGet/orElseThrow/ifPresentOrElse — never call .get() unchecked.

Checklist

  • I can explain, in my own words, the casting problem generics remove, and what type erasure means.
  • I wrote my own generic class with at least one type parameter, and a generic method with a bounded type parameter.
  • I implemented Comparable on a class and separately wrote a Comparator chain (.reversed().thenComparing(...)) for a different order.
  • I can say which List/Set/Map implementation to pick for "no order needed," "keep insertion order," and "always sorted," and used ArrayDeque as both a stack and a queue.
  • I wrote a lambda for at least Predicate, Function and Consumer, and composed two of them.
  • I replaced a lambda with each of the four kinds of method reference.
  • I built a streams pipeline with filter/map/sorted and at least one Collectors.groupingBy.
  • I can explain why streams are lazy, and showed it with a counter that stays at zero until a terminal operation runs.
  • I used Optional for a lookup that can fail, and resolved it with orElse/orElseThrow/ifPresentOrElse instead of a null check.

Search the guide