Skip to Content
Course content

52: Practice Exercise: Building a Student Grade Book with Collections

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've spent a few lessons talking about the theory of List and Map, but it's a different beast when you're staring at a blank IDE. To really get this to click, I want to walk you through building a small Student Grade Book. It's a classic problem because it forces us to think about how to associate a piece of data (a grade) with a unique identifier (a student's name) and then manipulate that data later.

Picking the right tool for the job

When I first start a project like this, I ask myself: "How am I going to look up this data?" If I need to find a student's grade quickly without looping through a whole list, a HashMap is the obvious choice. It gives us that O(1) average time complexity for lookups, which is exactly what we want for a grade book.

public class GradeBook {
    private Map<String, Integer> studentGrades = new HashMap<>();

    public void addGrade(String studentName, int grade) {
        studentGrades.put(studentName, grade);
    }

    public Integer getGrade(String studentName) {
        return studentGrades.get(studentName);
    }
}

Simple enough, right? I'm using Integer instead of int in the Map because collections can't hold primitives. Java handles the boxing and unboxing for us, so we don't have to sweat it too much.

Calculating the class average

Now, usually, a teacher doesn't just want individual grades; they want the average. To do this, I need to iterate over the values in my map. I'll use the values() collection, which is a handy way to ignore the keys (the names) and just focus on the numbers.

public double getClassAverage() {
    if (studentGrades.isEmpty()) return 0.0;

    double sum = 0;
    for (int grade : studentGrades.values()) {
        sum += grade;
    }
    return sum / studentGrades.size();
}

The "Wait, how do I sort this?" moment

Here is where I usually trip up when I'm rushing. I wanted to print a "Leaderboard" of students from highest to lowest grade. My first instinct was to try and sort the HashMap directly. I tried calling Collections.sort(studentGrades) and, predictably, the compiler screamed at me. You can't sort a Map because, by definition, a HashMap doesn't guarantee any specific order.

I had to stop and pivot. To sort the data, I need to move the Map entries into a List, because Lists are orderable. It's a common pattern: use a Map for storage and lookup, but convert to a List when you need to sort or paginate.

Fixing the sorting logic

To fix this, I'll extract the entrySet(), dump it into an ArrayList, and then use a custom comparator. I'll use Comparator.comparingInt to keep the code clean and readable.

import java.util.*;

public void printLeaderboard() {
    // Convert map entries to a list so we can actually sort them
    List<Map.Entry<String, Integer>> sortedList = new ArrayList<<Map.Entry<String, Integer>>>(studentGrades.entrySet());

    // Sort descending: higher grades first
    sortedList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

    System.out.println("--- Class Leaderboard ---");
    for (Map.Entry<String, Integer> entry : sortedList) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}

See what happened there? We didn't change the original studentGrades map—which is good, because we still want those fast lookups—we just created a temporary sorted view of the data for the report.




📋 Practical Task

Exercise: Implementing a Grade-Based Filter for the GradeBook

Now it's your turn to extend the GradeBook class. In a real-world scenario, a teacher often needs to identify "at-risk" students who are scoring below a certain threshold so they can provide extra help.

Your Task: Add a new method to the GradeBook class called getStudentsBelowGrade(int threshold).

  • The method should take an int as a parameter (the threshold).
  • It should return a List<String> containing the names of all students whose grade is strictly less than that threshold.
  • Ensure the list is returned in alphabetical order (use Collections.sort() on the resulting list).

Test your code: Add five students with varying grades, then call your method with a threshold of 65. Verify that only the students scoring 64 or lower are returned, and that their names are sorted A-Z.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.