Topic: Nested Collections

Write a method enrolledIn that takes a Map from student's names (Strings) to a set of classes they are enrolled in (Set<String>) and a number classes that returns a sorted Set of student's names who are enrolled in at least classes number of classes.

Example: If the enrollments is a Map with the following values

{"Hunter"=["CSE 143"], "Zach"=["CSE 143", "CSE 331"], "Miri=["CSE 143", "CSE 333", "CSE 390"], "Ayaz"=["GH 101", "MATH 308"]}
then enrolledIn(enrollments, 2) would return the set
["Ayaz", "Miri", "Zach"]


To test your code, you should make a new Map with the example values above and call your method to make sure it produces the right output, testing code is provided for you if you want.
import java.util.*;

public class EnrolledInTest {

    public static void main(String[] args) {
        Map<String, Set<String>> enrollments = new HashMap<String, Set<String>>();

        addEnrollments(enrollments, "Zach", "CSE 143");
        addEnrollments(enrollments, "Zach", "CSE 331");

        addEnrollments(enrollments, "Hunter", "CSE 143");

        addEnrollments(enrollments, "Miri", "CSE 333");
        addEnrollments(enrollments, "Miri", "CSE 390");
        addEnrollments(enrollments, "Miri", "CSE 143");

        addEnrollments(enrollments, "Ayaz", "GH 101");
        addEnrollments(enrollments, "Ayaz", "MATH 308");

        System.out.println("enrolledIn returned: " + enrolledIn(enrollments, 2));


    // Adds the given class to the set in the map for the given name. If there isn't a name, add a new entry
    public static void addEnrollments(Map<String, Set<String>> enrollments, String name, String className) {
        if (!enrollments.containsKey(name)) {
            enrollments.put(name, new TreeSet<String>());



Click here if you want to see the solution. Note: You can't unsee it so try to do the problem first.
public static Set<String> enrolledIn(Map<String, Set<String>> enrollments, int classes) {
    Set<String> names = new TreeSet<String>(); // TreeSet is important for sorted

    for (String name : enrollments.keySet()) {
        if (enrollments.get(name).size() >= classes) {

    return names;