Start learning free

LESSON 202 OF 671 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Java: Grades by Subject with a TreeMap

Practice Read the full explanation

Use a dictionary, a loop, and conditionals to print each subject with its letter grade in alphabetical order.

You start with:

TreeMap<String, Integer> grades = new TreeMap<>();
grades.put("Math", 92);
grades.put("English", 78);
grades.put("Science", 85);
grades.put("History", 67);

Build:

English: C
History: D
Math: A
Science: B

Rules:

  • Visit the subjects in alphabetical order.
  • Look up each subject's score in the dictionary and apply the grading scale (90+ A, 80s B, 70s C, 60s D, else F).
  • On each iteration print the subject, a colon and a space, then the grade, for example English: C.

Use a TreeMap - it iterates its keys in sorted order automatically.

TreeMap<String, Integer> grades = new TreeMap<>();
grades.put("Math", 92);
grades.put("English", 78);
grades.put("Science", 85);
grades.put("History", 67);

for (String subject : grades.keySet()) {
    int score = grades.get(subject);
    String grade;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    System.out.println(subject + ": " + grade);
}

STEP 1 OF 9
    Ctrl + Enter to check

    JAVA · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Java, explained

    Problem overview

    In version 5 the scores are no longer in parallel arrays. A TreeMap<String, Integer> named grades maps each subject to its score: Math 92, English 78, Science 85 and History 67. The program prints one line per subject, in alphabetical order, with the subject, a colon, a space and the letter grade from the same scale as before (90 or more A, 80 to 89 B, 70 to 79 C, 60 to 69 D, below 60 F).

    English: C
    History: D
    Math: A
    Science: B
    

    The starting data was filled in the order Math, English, Science, History, so the output order comes from the map, not from the order of the put calls.

    Approach: loop over the keys, look up each score

    A map stores key-value pairs, and here the key is the subject name and the value is the score. To visit every subject, the program loops over the map's keys, and for each key it looks up the value. The grading ladder from the earlier versions then turns that score into a letter.

    The alphabetical order is the reason for choosing a TreeMap. A TreeMap keeps its keys sorted, so keySet() returns them from A to Z, and no sorting code is needed. A HashMap makes no promise about order: the same four subjects can come out in a different sequence, which would break the expected output.

    Compared with version 4, the grading ladder is exactly the same. Only the source of the pairs changes: version 4 read two arrays by position, and this version reads one map by key. Because a map ties each name to its score, the two values can no longer drift out of step the way two arrays of different lengths can.

    Step by step

    1. Loop over the keys. for (String subject : grades.keySet()) gives each subject in turn. This is an enhanced for loop: subject takes the next key on every pass. Close the brace right away so the following lines go inside.
    2. Look up the score. int score = grades.get(subject); asks the map for the value stored under that key.
    3. Declare grade. String grade; with no value, because the ladder sets it.
    4. Start the ladder at the top. If score is at least 90, grade is "A".
    5. Add else if for 80 or more to give "B". It runs only when the score is below 90.
    6. Add else if for 70 or more to give "C".
    7. Add else if for 60 or more to give "D".
    8. End with else to give "F", so every subject ends up with a grade.
    9. Print inside the loop. The subject, a colon and a space, and then the grade. Being inside the loop, this prints once per subject, so there are four lines.

    The solution in Java

    TreeMap<String, Integer> grades = new TreeMap<>();
    grades.put("Math", 92);
    grades.put("English", 78);
    grades.put("Science", 85);
    grades.put("History", 67);
    
    for (String subject : grades.keySet()) {
        int score = grades.get(subject);
        String grade;
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else if (score >= 60) {
            grade = "D";
        } else {
            grade = "F";
        }
        System.out.println(subject + ": " + grade);
    }
    

    The Java details worth a closer look:

    • Generics need wrapper types. A map's values can't be the primitive int, so the type is Integer. Java converts between the two automatically: put("Math", 92) boxes the number and int score = grades.get(subject) unboxes it.
    • Sorted keys. grades.keySet() prints as [English, History, Math, Science]. Strings sort by their characters, so a capital letter comes before any lower-case one. A map with the keys math, English and Art prints as {Art=3, English=2, math=1}, with the lower-case key last.
    • get returns null for a missing key. Unboxing null into an int throws NullPointerException. Inside this loop that can't happen, because the keys come from the map itself.
    • Entries instead of keys. A loop over grades.entrySet() gives each key and its value together, so no get call is needed: entry.getKey() and entry.getValue() read the two halves. The order is the same sorted order. The lesson loops over the keys, which keeps the lookup visible.
    • One key, one value. Putting the same key again replaces its value. After grades.put("Math", 55), the map still has four entries and grades.get("Math") is 55.

    Complexity

    Time: O(n log n) for n subjects. Each put into a TreeMap costs O(log n), and each get in the loop does too. The loop itself makes n passes with a constant-size ladder in each.

    Space: O(n), for the entries stored in the map.

    Edge cases and common mistakes

    • Using a HashMap. The map type decides the order. A HashMap holding these four subjects doesn't have to list them alphabetically, and the order can change with the data.
    • Looping over the wrong thing. grades.keySet() gives the subjects. Looping over grades.values() gives scores with no names attached.
    • Looking up a subject that isn't there. grades.get("Art") is null, and assigning it to an int throws NullPointerException.
    • Boundary scores. 90 is an A and 60 is a D. After grades.put("Math", 55) the Math line becomes an F.

    Testing

    • The starting map prints English: C, History: D, Math: A and Science: B, in that order.
    • An empty TreeMap prints nothing, as the loop body never runs.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free