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
- Loop over the keys.
for (String subject : grades.keySet())gives each subject in turn. This is an enhancedforloop:subjecttakes the next key on every pass. Close the brace right away so the following lines go inside. - Look up the score.
int score = grades.get(subject);asks the map for the value stored under that key. - Declare
grade.String grade;with no value, because the ladder sets it. - Start the ladder at the top. If
scoreis at least 90,gradeis"A". - Add
else iffor 80 or more to give"B". It runs only when the score is below 90. - Add
else iffor 70 or more to give"C". - Add
else iffor 60 or more to give"D". - End with
elseto give"F", so every subject ends up with a grade. - 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 isInteger. Java converts between the two automatically:put("Math", 92)boxes the number andint 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 keysmath,EnglishandArtprints as{Art=3, English=2, math=1}, with the lower-case key last. getreturnsnullfor a missing key. Unboxingnullinto anintthrowsNullPointerException. 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 nogetcall is needed:entry.getKey()andentry.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 andgrades.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. AHashMapholding 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 overgrades.values()gives scores with no names attached. - Looking up a subject that isn't there.
grades.get("Art")isnull, and assigning it to anintthrowsNullPointerException. - 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: AandScience: B, in that order. - An empty
TreeMapprints nothing, as the loop body never runs.
