Managing Student Enrollments Using Java HashMap and ArrayList

In this lesson, we'll learn how to manage student enrollments using Java's HashMap and ArrayList collections. These data structures allow efficient data organization and access, which are essential for building an enrollment system. We'll implement methods to handle enrolling and unenrolling students, checking enrollment status, and listing students in a course. This practical approach will enhance your understanding of these structures. Now, let's dive into the methods we need to implement.

Introducing Methods to Implement

Here are the methods we need to implement in our enrollment system:

  • enroll(String student, String course): This method adds a student to a course. If the student is already enrolled, it does nothing.
  • unenroll(String student, String course): This method removes a student from a course. It returns true if the student was enrolled and has now been removed. Otherwise, it returns false. If, after unenrolling the student, the course becomes empty (no one is enrolled there), remove the course as well.
  • isEnrolled(String student, String course): This method checks if a student is enrolled in a course. It returns true if the student is enrolled and false otherwise.
  • listStudents(String course): This method returns an ArrayList<String> of all students enrolled in a given course. If no students are enrolled, it returns an empty ArrayList<String>.

Let's look at how to implement each of these methods step by step.

Step 1: Define the Class

We'll start by defining our class and then add each method one by one.

First, we define our EnrollmentSystem class:

Java
import java.util.ArrayList;
import java.util.HashMap;

class EnrollmentSystem {
    private HashMap<String, ArrayList<String>> enrollments;

    public EnrollmentSystem() {
        enrollments = new HashMap<>();
    }
}

public class Solution {
    public static void main(String[] args) {
        EnrollmentSystem es = new EnrollmentSystem();
        System.out.println("EnrollmentSystem initialized.");
    }
}

This code initializes an EnrollmentSystem class with a HashMap named enrollments that maps courses to lists of students.

Step 2: Implement Enroll Method
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal