1. Reference Guide

Key Topics: CB / AP CSA in Practice

Prior knowledge Real Java from this assignment Where / quick check
new / constructors new Expertise(2, "Data & AI", "analytics, ML, datasets") Popcorn, Expertise.catalog(): new creates an object by calling its constructor. Match the arguments to (int rank, String area, String focus). Which argument sets area?
Integer rank comparison Integer.compare((Integer) this.getValue("Rank"), (Integer) o.getValue("Rank")) Popcorn, Expertise.compareTo: cast the Rank values to Integer and compare them. Which comes first: rank 0 or rank 2?
String.compareTo String nameA = ((String) this.getValue("Name")).toLowerCase();
String nameB = ((String) o.getValue("Name")).toLowerCase();
nameA.compareTo(nameB)
HW #1, Mentor.compareTo: cast the Name values to String, then lowercase both for case-insensitive name order. Does frank come before Grace?
Enhanced for loop: for (Type item : items) for (Object[] row : rows) { ... } HW #2, loadMentors: each iteration gives you one row, not its index. Which type belongs before row?
1D array: one row’s values Object[] row = rows[0]; then (String) row[2] HW #2, loadMentors: row[2] is one Name; row.length counts columns. The cast reads that Object value as a String; it does not create a Mentor.
2D array: rows and columns Object[][] rows = MentorDatabase.MENTOR_ROWS; HW #2, mentor database: rows[0][2] is the first row’s Name. Indices start at 0; rows.length counts rows. What does rows[0][1] hold?

Follow the data: Object[][] rows -> Object[] row -> cast column values -> new Mentor(...) -> mentors.add(mentor).

Compare connection: negative = before, zero = tied, positive = after. Each class’s compareTo(Collectable o) supplies the natural order used by registry.sortNatural().

Mira Costa CS112 Core Object-Oriented & Collection Standards

Course Standard Core Concept / Skill Implementation Artifact in OCS Architecture
CS112-OOP-1 Interfaces & Polymorphism Collectable interface defining contracts (getMap, getKeys, getValue, compareTo) implemented by Animal, Student, and attribute components.
CS112-OOP-2 Generic Types & Bounded Containers Catalog<T extends Collectable> enforcing type safety while preserving reusable storage behavior across different data types.
CS112-DS-1 Linear Data Structures & Custom Maps Registry utilizing ArrayList, LinkedHashMap, and Map.computeIfAbsent for dynamic grouping and categorization.
CS112-ALG-1 Sorting & Ordering Algorithms Natural sorting via Comparable.compareTo and alternate dynamic field-based sorting via Java Comparator lambdas.

Mira Coast CS113 Advanced Data Structures & Analysis Standards

Course Standard Core Concept / Skill Implementation Artifact in OCS Architecture
CS113-DS-2 Projected Views & Decorator Pattern ProjectedCollectable wrapper record restructuring map projections to surface primary search/sort keys as the lead column.
CS113-ALG-2 Algorithm Efficiency & Indexing Dynamic field lookup evaluation (getValue(key)) across heterogeneous item collections to support flexible sorting and searching without redundant structures.
CS113-TEST-1 Boundary & Invariant Verification Handling edge cases across sorting inputs (empty catalogs, singletons, duplicate matches, and missing attribute keys).
CS113-PBL-1 Project Integration & Architecture Mapping domain entities (student records, pathways, standings) directly to data stores, making application state inspectable and web-ready.

2. Lesson Plan

Introduce the lesson layout and work through the Popcorn Hack together. Leave the Homework Hacks for self-study.

Challenge Context and Purpose

The OCS mentor dashboard shows which capstone projects each mentor supports. To recruit the right mentors, OCS needs to answer: which projects still need help, and what skills do they need?

Each hack builds on the last: describe the skills projects need, organize mentor information, explore who is available, then identify where more help is needed.

This is a simplified learning exercise, not a complete production system. A production solution would likely use POJOs to model records and consider JPA for database persistence.

Tech Talk (5-10 minutes)

Help students start the Popcorn Hack, run it to see feedback, and save their work. Before they continue independently, make sure they understand what each Homework Hack adds.

3. Code Review

Write it once, use it in the next hack. Each Homework Hack can reuse saved work from earlier hacks, so you can focus on the next step instead of copying code.

Label in the code What it means
@provides Foundation … @end Foundation Shares this part of your saved work with later hacks. Popcorn shares both Foundation and Expertise.
@dependency Foundation … @end Foundation Reserves a place to bring in that shared work using Update dependency.
flowchart TD
    P["Popcorn: save Foundation + Expertise"]
    H1["HW #1: build and save Mentor"]
    H2["HW #2: build and save MentorCatalog"]
    H3["HW #3: find mentor gaps"]
    P -->|Foundation + Expertise| H1
    P -->|Foundation + Expertise| H2
    P -->|Foundation + Expertise| H3
    H1 -->|Mentor| H2
    H1 -->|Mentor| H3
    H2 -->|MentorCatalog| H3

Before the first Run in each homework runner:

  1. Save your work in the earlier runners. Only saved changes can be transferred.
  2. Choose Update all in Dependencies, then click Update dependency. Leave the dependency labels in place.
  3. Save this runner, then Run. Your work on the current hack stays in place.

4. Hacks & Practice Tasks

Build one useful result at a time: skills catalog -> mentor records -> mentor catalog -> recruiting gaps. Each hack has a Data Shape table, a Code Concepts table, and a runner that shows your progress.

Popcorn Hack: Build an Expertise Catalog (In Class, 20%)

Describe the skills projects need. A Catalog<Expertise> holds Expertise objects; each object’s getMap() exposes Rank, Area, and Focus. Show insertion order, then natural rank order.

Homework Hack #1: Shape and Test Mentor Records (20%)

Reuse Expertise to describe a mentor’s skills. Build the Mentor table attributes, then test and sort a trio of mentors by name.

Homework Hack #2: Build, Sort, and Group a Mentor Catalog (30%)

Turn database rows into six valid Mentor objects. Show name order, available-slot order, and expertise groups. Save MentorCatalog as the next runner’s dependency.

Homework Hack #3: Find the Remaining Mentor Gaps (30%)

Reuse the mentor catalog. Show which projects need help, how many slots are available, and which areas still need recruits.

Grading Plan (1 Point Total)

Hack Weight What earns the points
Popcorn: Expertise Catalog 20% Rank/Area/Focus map, four objects, insertion vs natural rank order shown and explained.
HW #1: Mentor Records 20% Reused Expertise, derived Org and Open Slots, Ada’s row and sorted trio shown and explained.
HW #2: Mentor Catalog 30% Bad row skipped, six mentors loaded, both sorts and four groups shown, reusable MentorCatalog saved.
HW #3: Mentor Gaps 30% Filtered projects, demand counts, slot totals, and positive gaps shown; explain why Backend needs 2 recruits.

Each hack is scored on its own. Specific output lines, edge cases, and explained reasoning score highest.

The AP CSA Check is formative and does not change the one-point score. The required reflection is collected as individual evidence of learning and lesson feedback.

MCQ Check (Before Coding)

Answer these multiple-choice questions before opening the coding runners. Use the explanations to check your reasoning, then apply the same comparison rules in the Popcorn Hack.

AP CSA Collectables Check

Check each answer as many times as you need. Your last saved answers are the ones submitted.

Popcorn Hack: Build an Expertise Catalog

Purpose: describe the skills projects need, then put those skills in a useful priority order. Build simple Expertise objects and collect them in a Catalog<Expertise>.

Data Shape: one Expertise object’s map per catalog row

Keys are "Rank", "Area", "Focus"; values come from the object’s fields. Lower Rank means earlier in natural order.

Rank Area Focus
0 Frontend UI, SASS, accessibility
1 Backend APIs, Spring, databases
2 Data & AI analytics, ML, datasets
3 DevOps deployment, AWS, Docker

Code Concepts: fields -> map -> catalog -> sorted view

Build Java source / shape Why / visible progress
Define the map in getMap() Map<String, Object> map = new LinkedHashMap<>(); Given: preserve the order in which you insert keys.
Fill the map map.put("Rank", this.rank); then add Area and Focus Replace the Area-only entry; print all three keys in table order.
Build the Expertise catalog Catalog<Expertise> catalog = new Catalog<>();
catalog.add(new Expertise(2, "Data & AI", "analytics, ML, datasets"));
Given Data & AI first; add Frontend, Backend, DevOps from the table. Four objects, not four maps added directly.
Define natural order return Integer.compare(/* this rank */, (Integer) o.getValue("Rank")); In compareTo, replace return 0 so lower ranks come first.
Show both views areas.display();
new Registry(areas).sortNatural().forEach(System.out::println);
Given in main: compare original insertion order with natural rank order.

Run after each edit: first inspect the three map keys; next look for four rows; finally compare Data & AI first in insertion order with Frontend, Backend, Data & AI, DevOps in natural order. Finish at 3/3. Why is the sorted view not alphabetical?

Code Runner Challenge

Popcorn Hack - finish the Expertise TODOs, then Run until 3/3

View IPYNB Source
// CODE_RUNNER: Popcorn Hack - finish the Expertise TODOs, then Run until 3/3
import java.util.*;

// ===== Lesson foundation (given, do not edit) =====
/** @provides Foundation */

/** Contract for every dashboard record: project fields into a map, sort naturally. */
interface Collectable extends Comparable<Collectable> {
    Map<String, Object> getMap();
    List<String> getKeys();
    Object getValue(String key);
}

/** Shared code: subclasses only write getMap() and compareTo(). */
abstract class AbstractCollectable implements Collectable {
    public List<String> getKeys() { return new ArrayList<>(getMap().keySet()); }
    public Object getValue(String key) { return getMap().get(key); }
    public String toString() { return getMap().toString(); }
}

/** A typed list of collectables. */
class Catalog<T extends Collectable> {
    private final List<T> items = new ArrayList<>();
    public void add(T item) { items.add(item); }
    public List<T> getItems() { return items; }
    public void display() { items.forEach(System.out::println); }
}

/** Sorts, orders, and groups any catalog by its map keys. */
class Registry {
    private final List<Collectable> items;
    public Registry(Catalog<? extends Collectable> catalog) { items = new ArrayList<>(catalog.getItems()); }

    /** Prints the sort key first. */
    record ProjectedCollectable(Collectable delegate, String primaryKey) implements Collectable {
        public Map<String, Object> getMap() {
            Map<String, Object> original = delegate.getMap();
            Map<String, Object> reordered = new LinkedHashMap<>();
            if (original.containsKey(primaryKey)) reordered.put(primaryKey, original.get(primaryKey));
            original.forEach((k, v) -> { if (!k.equals(primaryKey)) reordered.put(k, v); });
            return reordered;
        }
        public List<String> getKeys() { return new ArrayList<>(getMap().keySet()); }
        public Object getValue(String key) { return getMap().get(key); }
        public int compareTo(Collectable o) { return delegate.compareTo(o); }
        public String toString() { return getMap().toString(); }
    }

    public List<Collectable> sortNatural() {
        List<Collectable> sorted = new ArrayList<>(items);
        Collections.sort(sorted);
        return sorted;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public List<Collectable> sortByField(String key) {
        List<Collectable> sorted = new ArrayList<>(items);
        sorted.sort((a, b) -> {
            Object valA = a.getValue(key), valB = b.getValue(key);
            return (valA instanceof Comparable && valB instanceof Comparable) ? ((Comparable) valA).compareTo(valB) : 0;
        });
        return sorted;
    }

    public List<ProjectedCollectable> orderBy(String key) {
        return sortByField(key).stream().map(item -> new ProjectedCollectable(item, key)).toList();
    }

    public Map<Object, List<Collectable>> groupBy(String key) {
        Map<Object, List<Collectable>> groups = new LinkedHashMap<>();
        for (Collectable item : items) groups.computeIfAbsent(item.getValue(key), k -> new ArrayList<>()).add(item);
        return groups;
    }
}

/** @end Foundation */

// ===== Popcorn Hack: Expertise =====

/**
 * A mentoring area. Natural order is rank, not alphabetical.
 * @provides Expertise
 */
class Expertise extends AbstractCollectable {
    private final int rank;
    private final String area;
    private final String focus;

    Expertise(int rank, String area, String focus) {
        this.rank = rank;
        this.area = area;
        this.focus = focus;
    }

    public String getArea() { return area; }

    public Map<String, Object> getMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("Area", area);
        // TODO 1: replace the Area-only entry above with Rank, Area, Focus in that order.
        // map.put("Rank", /* matching field */);
        // Use the same map.put("key", field) shape for Area and Focus; see the table.
        return map;
    }

    public int compareTo(Collectable o) {
        // TODO 2: replace return 0 using the comparison sources in the table.
        // return Integer.compare(/* this rank */, /* other rank */);
        // Other rank: (Integer) o.getValue("Rank"). Negative means this object comes first.
        return 0;
    }

    static Catalog<Expertise> catalog() {
        Catalog<Expertise> catalog = new Catalog<>();
        catalog.add(new Expertise(2, "Data & AI", "analytics, ML, datasets"));
        // TODO 3: keep Data & AI first; add Frontend (0), Backend (1), DevOps (3).
        // catalog.add(new Expertise(/* rank */, /* area string */, /* focus string */));
        // Fill arguments from the table. The given main compares insertion with rank order.
        return catalog;
    }

    /** Throws for an unknown area, so bad database rows get caught. (given) */
    static Expertise find(Catalog<Expertise> catalog, String area) {
        for (Expertise e : catalog.getItems()) if (e.getArea().equals(area)) return e;
        throw new IllegalArgumentException("unknown expertise " + area);
    }
}

/** @end Expertise */

// ===== Run Popcorn Hack =====
public class Main {
    public static void main(String[] args) {
        Catalog<Expertise> areas = Expertise.catalog();
        System.out.println("=== Expertise, insertion order ===");
        areas.display();
        System.out.println("\n=== Expertise, natural sort (rank) ===");
        new Registry(areas).sortNatural().forEach(System.out::println);

        System.out.println("\n=== Self-Check: Popcorn Hack ===");
        List<Object> sorted = new ArrayList<>();
        new Registry(areas).sortNatural().forEach(e -> sorted.add(e.getValue("Area")));
        check("4 areas in the catalog", areas.getItems().size() == 4);
        check("getMap() keys are Rank, Area, Focus",
              !areas.getItems().isEmpty() && areas.getItems().get(0).getKeys().equals(List.of("Rank", "Area", "Focus")));
        check("natural sort is Frontend, Backend, Data & AI, DevOps",
              sorted.equals(List.of("Frontend", "Backend", "Data & AI", "DevOps")));
        System.out.println(passed + "/" + total + " Popcorn Hack checks passed");
    }

    static int passed = 0, total = 0;

    static void check(String name, boolean ok) {
        total++;
        if (ok) passed++;
        System.out.println((ok ? "PASS " : "FAIL ") + name);
    }
}
Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack #1: Shape and Test Mentor Records

Purpose: turn a mentor’s contact details, skills, and capacity into one readable dashboard row. Then test three records and find them in name order.

Before Run: save Popcorn. Here choose Update all in Dependencies, click Update dependency, then save. This fills the empty Foundation and Expertise regions; your Mentor TODOs stay unchanged.

Data Shape: Ada’s Mentor map

A Mentor has an Expertise object from Popcorn. Reuse it; the Mentor map displays its Area, not a second copy of the full skills map.

Map key Value source Ada’s displayed value
"Name" name (given) Ada Rivera
"UID" uid (given) arivera
"Org" getOrg() techcorp.example
"Expertise" expertise.getArea() Backend
"Assigned" assigned 1
"Open Slots" getOpenSlots() 1

Code Concepts: derive values -> fill the row -> test a trio

Build Java source / shape Why / visible progress
Derive Org email.indexOf("@") then email.substring(/* index + 1 */) getOrg() returns techcorp.example, without the @.
Derive Open Slots capacity - assigned getOpenSlots() returns 1 for Ada; no extra stored field to keep in sync.
Fill getMap() Map<String, Object> map = new LinkedHashMap<>();
map.put("Org", getOrg());
Keep Name and UID; add the four missing keys using the Data Shape table.
Define name order String nameA = name.toLowerCase();
String nameB = ((String) o.getValue("Name")).toLowerCase();
return nameA.compareTo(nameB);
Replace return 0 in compareTo; frank belongs with the F’s.
Test three objects new Mentor(/* uid, name, email, expertise, capacity, assigned */)
trio.add(grace); trio.add(ada); trio.add(frank);
Given in main: three constructor examples, deliberately added out of name order.
Show the sorted trio new Registry(trio).sortNatural() Given print loop: Ada Rivera, frank kim, Grace Nguyen.

Run after each edit: verify Org, then Open Slots, then all six map keys, then name order. Finish at 4/4 and save Mentor for HW #2. Why calculate Org and Open Slots instead of storing them again?

Code Runner Challenge

Homework Hack #1 - finish the Mentor TODOs, then Run until 4/4

View IPYNB Source
// CODE_RUNNER: Homework Hack #1 - finish the Mentor TODOs, then Run until 4/4
import java.util.*;

// Before Run: save Popcorn, then Dependencies -> Update all -> Update dependency -> Save.
/** @dependency Foundation */
/** @end Foundation */

/** @dependency Expertise */
/** @end Expertise */

// ===== Homework Hack #1: Mentor =====

/**
 * A mentor record. HAS-A Expertise.
 * @provides Mentor
 */
class Mentor extends AbstractCollectable {
    private final String uid, name, email;
    private final Expertise expertise;
    private final int capacity, assigned;

    Mentor(String uid, String name, String email, Expertise expertise, int capacity, int assigned) {
        this.uid = uid;
        this.name = name;
        this.email = email;
        this.expertise = expertise;
        this.capacity = capacity;
        this.assigned = assigned;
    }

    public Expertise getExpertise() { return expertise; }

    public String getOrg() {
        // TODO 1: replace return ""; find "@" with email.indexOf("@"), then start one later.
        // return email.substring(/* separator index + 1 */);
        return "";
    }

    public int getOpenSlots() {
        // TODO 2: replace return 0 with capacity minus assigned. Ada: 2 - 1 = 1.
        // return /* available capacity */;
        return 0;
    }

    public Map<String, Object> getMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("Name", name);
        map.put("UID", uid);
        // TODO 3: keep Name and UID; add Org, Expertise, Assigned, Open Slots from the map table.
        // map.put("Org", /* method call */);
        // Expertise uses expertise.getArea(), not the Expertise object itself.
        return map;
    }

    public int compareTo(Collectable o) {
        // TODO 4: replace return 0; reference the AP CSA comparison table.
        // String nameA = name.toLowerCase();
        // String nameB = ((String) o.getValue("Name")).toLowerCase();
        // return /* compare nameA with nameB */;
        return 0;
    }
}

/** @end Mentor */

// ===== Run Homework Hack #1 =====
public class Main {
    public static void main(String[] args) {
        Expertise backend = new Expertise(1, "Backend", "APIs, Spring, databases");
        Mentor ada = new Mentor("arivera", "Ada Rivera", "ada.rivera@techcorp.example", backend, 2, 1);
        Mentor frank = new Mentor("fkim", "frank kim", "frank@designlab.example", backend, 2, 0);
        Mentor grace = new Mentor("gnguyen", "Grace Nguyen", "grace@chainco.example", backend, 1, 0);

        System.out.println("=== Ada's dashboard row ===");
        System.out.println(ada);
        System.out.println("Org: " + ada.getValue("Org") + ", Open Slots: " + ada.getValue("Open Slots"));

        Catalog<Mentor> trio = new Catalog<>();
        trio.add(grace);
        trio.add(ada);
        trio.add(frank);
        System.out.println("\n=== Natural sort (name, ignoring case) ===");
        new Registry(trio).sortNatural().forEach(m -> System.out.println(m.getValue("Name")));

        System.out.println("\n=== Self-Check: Homework Hack #1 ===");
        check("getMap() has Name, UID, Org, Expertise, Assigned, Open Slots",
              ada.getKeys().containsAll(List.of("Name", "UID", "Org", "Expertise", "Assigned", "Open Slots")));
        check("Org is the email domain", "techcorp.example".equals(ada.getValue("Org")));
        check("Open Slots = capacity - assigned", Integer.valueOf(1).equals(ada.getValue("Open Slots")));
        check("natural sort ignores case (frank kim before Grace)", frank.compareTo(grace) < 0);
        System.out.println(passed + "/" + total + " Homework Hack #1 checks passed");
    }

    static int passed = 0, total = 0;

    static void check(String name, boolean ok) {
        total++;
        if (ok) passed++;
        System.out.println((ok ? "PASS " : "FAIL ") + name);
    }
}
Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack #2: Build, Sort, and Group a Mentor Catalog

Purpose: turn raw database rows into a reusable catalog of mentors. Show who is available and which skills they offer; leave recruiting decisions for HW #3.

Before Run: save Popcorn and HW #1. Here choose Update all in Dependencies, click Update dependency, then save. This fills Foundation, Expertise, and Mentor without replacing your catalog work.

Data Shape: database row -> Mentor object -> catalog

Read Ada’s row across into new Mentor(...), then add that object to Catalog<Mentor>. Its dashboard map comes from your completed Mentor class.

Database column Ada’s row value Cast / source hint new Mentor(...) parameter
row[0]: ID 1 No cast needed for the error message Not passed to Mentor
row[1]: UID "arivera" (String) row[1] 1. String uid
row[2]: Name "Ada Rivera" (String) row[2] 2. String name
row[3]: Email "ada.rivera@techcorp.example" (String) row[3] 3. String email
row[4]: Area "Backend" Expertise.find(areas, (String) row[4]) (given) 4. Expertise expertise: use the looked-up object
row[5]: Capacity 2 (Integer) row[5] -> unboxed to int 5. int capacity
row[6]: Assigned 1 (Integer) row[6] -> unboxed to int 6. int assigned

Code Concepts: load -> sort -> group -> reuse

Build Java source / shape Why / visible progress
1. Collect Mentor objects Catalog<Mentor> mentors = new Catalog<>();
for (Object[] row : rows) { ... }
In MentorCatalog.loadMentors, construct a Mentor from the row table and call mentors.add(mentor).
Resolve the skill object Expertise.find(areas, (String) row[4]) Given try/catch: row 7’s Blockchain area is unknown; report and skip it, keeping six mentors.
Show natural name order new Registry(mentors) then registry.sortNatural().forEach(System.out::println); Given in main: Ada, Ben, Chioma, Dev, Elena, frank. Uses Mentor’s compareTo.
2. Show availability order registry.orderBy("Open Slots").forEach(System.out::println); Complete the method chain in main: slots print 0, 0, 1, 1, 2, 2.
3. Group by expertise Map<Object, List<Collectable>> groups = registry.groupBy("Expertise"); Outer loop over groups.entrySet(): print entry.getKey() as the area. Inner loop over entry.getValue(): print mentor.getValue("Name").
Reuse the catalog Catalog<Mentor> mentors = MentorCatalog.catalog(); The named provider contains row data and your loader, not the demo Main. Save it for HW #3.

Run in three passes:

  1. Finish loading: inspect six name-sorted rows and Skipped row 7: unknown expertise Blockchain.
  2. Finish orderBy: inspect all six rows with Open Slots first, ascending.
  3. Finish groupBy: Backend has Ada/Dev; Frontend has Ben/frank; Data & AI has Chioma; DevOps has Elena. Four headings, six names.

Finish at 3/3, inspect the two student-written display sections, then save. HW #3 will import your MentorCatalog along with Foundation, Expertise, and Mentor.

Code Runner Challenge

Homework Hack #2 - build, sort, and group the MentorCatalog, then Run until 3/3

View IPYNB Source
// CODE_RUNNER: Homework Hack #2 - build, sort, and group the MentorCatalog, then Run until 3/3
import java.util.*;

// Before Run: save earlier runners, then Dependencies -> Update all -> Update dependency -> Save.
/** @dependency Foundation */
/** @end Foundation */

/** @dependency Expertise */
/** @end Expertise */

/** @dependency Mentor */
/** @end Mentor */

// ===== OCS mentor database (given) =====

/**
 * Mentor rows and their reusable catalog loader. Row 7 is bad data on purpose.
 * @provides MentorCatalog
 */
class MentorDatabase {
    // id, uid, name, email, expertise, capacity (max capstones), assigned (current capstones)
    static final Object[][] MENTOR_ROWS = {
        {1, "arivera", "Ada Rivera",    "ada.rivera@techcorp.example", "Backend",    2, 1},
        {2, "bchen",   "Ben Chen",      "ben@designlab.example",       "Frontend",   3, 3},
        {3, "cokafor", "Chioma Okafor", "chioma@datahub.example",      "Data & AI",  2, 0},
        {4, "dpatel",  "Dev Patel",     "dev@techcorp.example",        "Backend",    1, 1},
        {5, "elopez",  "Elena Lopez",   "elena@cloudops.example",      "DevOps",     2, 1},
        {6, "fkim",    "frank kim",     "frank@designlab.example",     "Frontend",   2, 0},
        {7, "gnguyen", "Grace Nguyen",  "grace@chainco.example",       "Blockchain", 1, 0},
    };
}

class MentorCatalog {
    static Catalog<Mentor> catalog() {
        return loadMentors(MentorDatabase.MENTOR_ROWS, Expertise.catalog());
    }

    static Catalog<Mentor> loadMentors(Object[][] rows, Catalog<Expertise> areas) {
        Catalog<Mentor> mentors = new Catalog<>();
        for (Object[] row : rows) {
            try {
                Expertise expertise = Expertise.find(areas, (String) row[4]);
                // TODO 1: replace the labels with casts from the Data Shape table.
                // Mentor mentor = new Mentor(
                //     UID, Name, Email, expertise, Capacity, Assigned
                // );
                // mentors.add(mentor);
            } catch (IllegalArgumentException e) {
                System.out.println("Skipped row " + row[0] + ": " + e.getMessage());
            }
        }
        return mentors;
    }
}
/** @end MentorCatalog */

// ===== Homework Hack #2: Build, Sort, and Group a Mentor Catalog =====
public class Main {

    public static void main(String[] args) {
        Catalog<Mentor> mentors = MentorCatalog.catalog();
        Registry registry = new Registry(mentors);

        System.out.println("\n=== 1. Mentors, natural sort (by Name) ===");
        registry.sortNatural().forEach(System.out::println);

        System.out.println("\n=== 2. Mentors, orderBy Open Slots ===");
        // TODO 2: use the availability-order row in Code Concepts to finish this chain.
        // registry.orderBy(/* quoted field name */).forEach(System.out::println);
        // Inspect slots: 0, 0, 1, 1, 2, 2.

        System.out.println("\n=== 3. Mentors, groupBy Expertise ===");
        // TODO 3: use the grouping row in Code Concepts to fill the two print statements.
        // Map<Object, List<Collectable>> groups = registry.groupBy("Expertise");
        // for (Map.Entry<Object, List<Collectable>> entry : groups.entrySet()) {
        //     // TODO: print the area's heading using entry.
        //     for (Collectable mentor : entry.getValue()) {
        //         // TODO: print this mentor's Name field.
        //     }
        // }
        // Inspect: four area headings, six names total.

        System.out.println("\n=== Self-Check: Homework Hack #2 ===");
        check("6 mentors loaded, bad Blockchain row skipped (needs Popcorn Hack and Homework Hack #1 finished)", mentors.getItems().size() == 6);
        check("groupBy(\"Expertise\") gives 4 groups", registry.groupBy("Expertise").size() == 4);
        List<Object> names = new ArrayList<>();
        registry.sortNatural().forEach(mentor -> names.add(mentor.getValue("Name")));
        check("natural name order reuses Mentor.compareTo", names.equals(List.of(
              "Ada Rivera", "Ben Chen", "Chioma Okafor", "Dev Patel", "Elena Lopez", "frank kim")));
        System.out.println(passed + "/" + total + " Homework Hack #2 checks passed");
    }

    static int passed = 0, total = 0;

    static void check(String name, boolean ok) {
        total++;
        if (ok) passed++;
        System.out.println((ok ? "PASS " : "FAIL ") + name);
    }
}
Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack #3: Find the Remaining Mentor Gaps

Purpose: decide where OCS still needs to recruit. Do not count mentors alone: compare projects without mentors against the open slots in each expertise area.

Before Run: save the completed earlier runners. Here choose Update all in Dependencies, click Update dependency, then save. This fills Foundation, Expertise, Mentor, and MentorCatalog. Capstone records and progress-printing code are given; you write three small transformations.

Data Shape: projects needing help - available slots = remaining gap

Each Capstone map has Project, Needs, and Mentors. Filter on Mentors == 0, group by Needs, then compare with the imported mentors’ capacity. These are the expected totals, not hardcoded answers to put in your methods.

Area (map key) Step 1: unmentored projects Step 2: open slots Step 3: demand - supply Recruit?
Backend 3 1 (Ada 1 + Dev 0) 2 Yes: 2
Frontend 1 2 (Ben 0 + frank 2) -1 No
Data & AI 1 2 (Chioma) -1 No
DevOps 0 1 (Elena) -1 No

Code Concepts: filter -> total -> subtract

Build Java source / shape Why / visible progress
1. unmentoredProjects(capstones) Catalog<Capstone> unmentored = new Catalog<>();
for (Capstone project : capstones.getItems()) { ... }
Keep only projects with no mentor; don’t change the source catalog.
Keep matching objects Integer.valueOf(0).equals(project.getValue("Mentors"))
unmentored.add(project);
Fill the if and its body. The given display prints the five remaining project maps.
Group the filtered catalog new Registry(unmentored).groupBy("Needs")
entry.getValue().size()
Given in main: print Backend = 3, Data & AI = 1, Frontend = 1.
2. openSlotsByArea(mentors) Map<String, Integer> openSlots = new LinkedHashMap<>();
for (Mentor mentor : mentors.getItems()) { ... }
One running total per area, rather than one entry per person.
Add each mentor’s capacity mentor.getExpertise().getArea()
mentor.getOpenSlots()
openSlots.merge(area, slots, Integer::sum);
Fill the source expressions and merge. Unlike put, merge adds to the existing total. Print all four area totals.
3. mentorGaps(demandGroups, openSlots) for (Map.Entry<Object, List<Collectable>> entry : demandGroups.entrySet()) { ... } For each demand group, use its area key to find matching supply.
Keep only unmet demand entry.getValue().size()
openSlots.getOrDefault(area, 0)
if (gap > 0) { gaps.put(area, gap); }
Fill demand, supply, and subtraction. The given comparison display shows the arithmetic; the returned map contains only positive gaps.

Run in three passes; the given main prints each result:

  1. Finish filtering: five project rows and three demand groups; 1/3 checks. Why are Robotics Scheduler and Library Check-In excluded?
  2. Finish slot totals: {Backend=1, Frontend=2, Data & AI=2, DevOps=1}; 2/3 checks.
  3. Finish gaps: Backend: 3 - 1 = 2, Data & AI: 1 - 2 = -1, Frontend: 1 - 2 = -1; final map {Backend=2}, then Recruit 2 Backend mentor(s); 3/3 checks.

Explain why DevOps has supply but no demand group, and why negative gaps are not recruiting requests. Assume one slot per unmentored project and one slot per new recruit.

Code Runner Challenge

Homework Hack #3 - filter demand, total supply, then find gaps; Run after each step until 3/3

View IPYNB Source
// CODE_RUNNER: Homework Hack #3 - filter demand, total supply, then find gaps; Run after each step until 3/3
import java.util.*;

// Before Run: save earlier runners, then Dependencies -> Update all -> Update dependency -> Save.
/** @dependency Foundation */
/** @end Foundation */

/** @dependency Expertise */
/** @end Expertise */

/** @dependency Mentor */
/** @end Mentor */

/** @dependency MentorCatalog */
/** @end MentorCatalog */

// ===== Capstone records (given) =====
class Capstone extends AbstractCollectable {
    private final String project, needs;
    private final int mentors;
    Capstone(String project, String needs, int mentors) {
        this.project = project;
        this.needs = needs;
        this.mentors = mentors;
    }
    public Map<String, Object> getMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("Project", project);
        map.put("Needs", needs);
        map.put("Mentors", mentors);
        return map;
    }
    public int compareTo(Collectable o) { return project.compareTo((String) o.getValue("Project")); }
    static Catalog<Capstone> catalog() {
        Object[][] rows = {
            {"Food Bank Tracker",    "Backend",   0},
            {"Robotics Scheduler",   "DevOps",    1},
            {"Library Check-In",     "Frontend",  1},
            {"Volunteer Hours",      "Data & AI", 0},
            {"Tutor Match",          "Backend",   0},
            {"Club Fair Map",        "Frontend",  0},
            {"Senior Center Portal", "Backend",   0},
        };
        Catalog<Capstone> catalog = new Catalog<>();
        for (Object[] row : rows) {
            catalog.add(new Capstone((String) row[0], (String) row[1], (Integer) row[2]));
        }
        return catalog;
    }
}

public class Main {
    static Catalog<Capstone> unmentoredProjects(Catalog<Capstone> capstones) {
        Catalog<Capstone> unmentored = new Catalog<>();
        // TODO 1: loop through the given projects; keep only those with zero mentors.
        // for (Capstone project : capstones.getItems()) {
        //     if (/* zero-mentor test from the Code Concepts table */) {
        //         // TODO: add project to unmentored.
        //     }
        // }
        return unmentored;
    }

    static Map<String, Integer> openSlotsByArea(Catalog<Mentor> mentors) {
        Map<String, Integer> openSlots = new LinkedHashMap<>();
        // TODO 2: total slots, not the number of people, using the Code Concepts table.
        // for (Mentor mentor : mentors.getItems()) {
        //     String area = /* Mentor -> Expertise -> area */;
        //     int slots = /* Mentor -> open slots */;
        //     // TODO: merge this mentor's slots into the area's total.
        // }
        return openSlots;
    }

    static Map<String, Integer> mentorGaps(Map<Object, List<Collectable>> demandGroups,
                                           Map<String, Integer> openSlots) {
        Map<String, Integer> gaps = new LinkedHashMap<>();
        // TODO 3: compare demand with matching supply; keep only positive gaps.
        // for (Map.Entry<Object, List<Collectable>> entry : demandGroups.entrySet()) {
        //     String area = (String) entry.getKey();
        //     int demand = /* group's list size */;
        //     int supply = /* area's total, default 0 */;
        //     int gap = /* demand minus supply */;
        //     if (gap > 0) {
        //         // TODO: store area and gap in gaps.
        //     }
        // }
        return gaps;
    }

    public static void main(String[] args) {
        Catalog<Mentor> mentors = MentorCatalog.catalog();
        Catalog<Capstone> capstones = Capstone.catalog();
        if (mentors.getItems().size() != 6) {
            throw new IllegalStateException("Finish and save HW #2, then Update all dependencies here; expected 6 mentors.");
        }

        System.out.println("\n=== 1. Projects that still need a mentor ===");
        Catalog<Capstone> unmentored = unmentoredProjects(capstones);
        unmentored.display();
        Map<Object, List<Collectable>> demandGroups = new Registry(unmentored).groupBy("Needs");
        Map<String, Integer> demandCounts = new LinkedHashMap<>();
        demandGroups.forEach((area, projects) -> demandCounts.put((String) area, projects.size()));
        System.out.println("Demand: " + demandCounts);
        check("five unmentored projects: Backend 3, Data & AI 1, Frontend 1",
              unmentored.getItems().size() == 5 && capstones.getItems().size() == 7
              && demandCounts.equals(Map.of("Backend", 3, "Data & AI", 1, "Frontend", 1))
              && unmentored.getItems().stream().allMatch(project -> Integer.valueOf(0).equals(project.getValue("Mentors"))));

        System.out.println("\n=== 2. Available mentor slots by area ===");
        Map<String, Integer> openSlots = openSlotsByArea(mentors);
        System.out.println("Open slots: " + openSlots);
        check("slot totals: Backend 1, Frontend 2, Data & AI 2, DevOps 1",
              openSlots.equals(Map.of("Backend", 1, "Frontend", 2, "Data & AI", 2, "DevOps", 1)));

        System.out.println("\n=== 3. Compare demand with supply ===");
        demandGroups.forEach((area, projects) -> {
            int demand = projects.size();
            int supply = openSlots.getOrDefault((String) area, 0);
            System.out.println(area + ": " + demand + " - " + supply + " = " + (demand - supply));
        });
        Map<String, Integer> gaps = mentorGaps(demandGroups, openSlots);
        System.out.println("Positive gaps: " + gaps);
        gaps.forEach((area, count) -> System.out.println("Recruit " + count + " " + area + " mentor(s)"));
        check("only Backend needs recruits, and it needs 2", gaps.equals(Map.of("Backend", 2)));
        System.out.println(passed + "/" + total + " Homework Hack #3 checks passed");
    }

    static int passed = 0, total = 0;
    static void check(String name, boolean ok) {
        total++;
        if (ok) passed++;
        System.out.println((ok ? "PASS " : "FAIL ") + name);
    }
}
Main.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Reflection

After completing Popcorn and all three Homework Hacks, answer both parts in your own words. Use evidence from your code, a Self-Check, or printed output so your response reflects your work rather than a sample answer.

Quick Validation Checklist

  • Each Self-Check passes: Popcorn 3/3, HW #1 4/4, HW #2 3/3, HW #3 3/3.
  • Foundation and Expertise come from saved Popcorn; Mentor and MentorCatalog come from their saved source runners. Update all before the first Run, and save each receiving runner too.
  • HW #3 shows filtered project rows, demand counts, open-slot totals, and positive gaps.
  • Every hack has a markdown cell with its output lines and your explanation.
  • The AP CSA Check and Reflection are saved and selected for submission.
  • The Blockchain row is skipped, not crashed on.
  • You submitted the GitHub .ipynb link, not a Pages link.

Above and beyond: add an Availability class (weekday/evening) and group mentors by it.

5. Lesson Revisions

Revision Made: Each hack leads with a purpose, Data Shape table, and Code Concepts table. Popcorn provides Foundation and Expertise; HW #1 provides Mentor; HW #2 provides MentorCatalog; HW #3 finds recruiting gaps. Later runners start with empty dependency regions instead of copied boilerplate. Section 3 diagrams the reuse path and explains Save -> Update all -> Save -> Run. HW #3 prints and checks each intermediate result. Weights are 20%, 20%, 30%, 30%; the MCQ and individual reflection remain.

6. Feedback Evidence

No learner feedback has been recorded for this revision yet. The reflection runner will collect student feedback to guide the next revision.

7. LxD Cycle Process

Empathize: The dashboard scenario gives learners a concrete reason to model expertise, mentors, and capstone needs as data they can inspect and organize.

Define: Learners need to connect getMap() and natural ordering to useful dashboard views, while handling a malformed database row without stopping the workflow.

Ideate: Introduce comparison reasoning with the MCQ, then build the solution in stages: Expertise catalog, Mentor records, reusable MentorCatalog, and recruiting gaps.

Prototype: One in-class Popcorn runner and three scaffolded Homework runners provide TODOs and Self-Checks. Saved dependencies carry earlier work forward; HW #3 exposes each transformation’s output. The reflection captures individual learning and a proposed lesson improvement.

Test: Use the Self-Check results and dashboard output to verify behavior. Review student reflections after teaching to identify unclear references or task instructions for the next revision.

8. References

College Board. (2025). AP Computer Science A course and exam description (effective fall 2025) and AP Java Quick Reference.

OCS. Abstract Collectables lesson.

Submit Assignment

Choose what to hand in: click Add to submission on each runner you want graded (hacks, popcorn hacks), and save it. Leaving out practice runners does not lower your grade, but a required hack you leave out is graded as missing. Your selection is sent as a Gist for automatic review.

    Need to update a submission later? Open the submissions dashboard.