Problem overview
Now the scores are stored by subject. The starter code builds a java.util.TreeMap that maps each subject name to its score:
val grades = java.util.TreeMap<String, Int>()
grades["Math"] = 92
grades["English"] = 78
grades["Science"] = 85
grades["History"] = 67
The program must visit the subjects in alphabetical order and print each one with its letter grade, using the usual scale (90 and up A, 80s B, 70s C, 60s D, otherwise F):
English: C
History: D
Math: A
Science: B
The subjects were inserted in a different order from the one printed. Producing the sorted order is part of the lesson.
Approach
A map stores key and value pairs, here subject and score. The job is to go through the keys, look up each score, run the grading ladder and print the line. The only new question is the order.
A TreeMap keeps its keys sorted at all times. For String keys, the order is alphabetical (strictly, the order of String.compareTo, which compares character codes). Iterating over grades.keys therefore visits English, History, Math and Science without any sorting step in your code.
Compare this with the previous version, where two arrays shared an index. A map removes that need: the score is stored under the subject's own name, so the two pieces of data can't drift out of step.
Step by step
- Loop over the keys.
for (subject in grades.keys)gives one subject name per pass, in sorted order. Close the loop's brace right away. - Look up the score.
grades[subject]returns the value stored under that key. In Kotlin a lookup in a map has the typeInt?, because the key might be missing. Ending with!!tells the compiler that this key is certainly there, and gives a plainInt. - Declare the grade.
var grade: Stringwith no value yet. The type has to be written because nothing is assigned. - Build the ladder.
if (score >= 90)gives"A", thenelse iftests for 80, 70 and 60 give"B","C"and"D", and a plainelsegives"F". As before, each test relies on the previous ones having failed. - Print inside the loop. After the ladder, print the subject, a colon and a space, then the grade. That makes one line per subject.
The solution in Kotlin
val grades = java.util.TreeMap<String, Int>()
grades["Math"] = 92
grades["English"] = 78
grades["Science"] = 85
grades["History"] = 67
for (subject in grades.keys) {
val score = grades[subject]!!
var grade: String
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"
}
println(subject + ": " + grade)
}
Kotlin details worth knowing:
- Calling a Java class. Kotlin runs on the JVM, so it can use Java's
TreeMapdirectly. The lesson writes the full namejava.util.TreeMapinstead of importing it. Kotlin also has its ownsortedMapOffunction, but the lesson uses the class. - Index syntax on a map.
grades["Math"] = 92callsput, andgrades[subject]callsget. Assigning to an existing key replaces its value, so the map never holds a key twice. - What
!!does. It convertsInt?toIntand throws aNullPointerExceptionif the value isnull. Here the keys come from the map itself, so the lookup can't fail. Writinggrades["Art"]for a subject that isn't in the map givesnull, and adding!!to that lookup would throw. - Why a plain
HashMapisn't enough. AHashMappromises no particular order. With these four subjects it happens to list the keys as[English, Science, Math, History], which is not alphabetical, and you shouldn't rely on any such order. TheTreeMapgives[English, History, Math, Science]. varversusvalforgrade. The lesson declaresvar grade: String. Each pass assigns it once, sovalwould also compile here, as it did in the previous version.
Following the loop
Printing grades itself shows the sorted order the loop relies on: {English=78, History=67, Math=92, Science=85}. The four passes are then:
| subject | score | First test that is true | Printed |
|---|---|---|---|
| English | 78 | score >= 70 | English: C |
| History | 67 | score >= 60 | History: D |
| Math | 92 | score >= 90 | Math: A |
| Science | 85 | score >= 80 | Science: B |
There is also a way to get the key and the value in one step, with destructuring: for ((subject, score) in grades) visits the entries in the same sorted order and removes the need for the lookup and the !!. The lesson uses the key loop because it makes the lookup explicit.
Edge cases and common mistakes
- Sorting is case sensitive. Uppercase letters sort before lowercase ones. With the keys
math,Zoology,Artandart, the loop visitsArt,Zoology,artand thenmath. The lesson's names all start with a capital letter, so it doesn't show up here. - Printing in the wrong place. A
printlnafter the loop would run once, andgradewould be out of scope there. - Duplicate keys. Setting
grades["Math"] = 50a second time replaces the 92. The map still has four entries, and Math is graded F. - A missing subject. Looking up a name that was never added, such as
grades["Art"], givesnull. Printing it showsnull, and adding!!makes it throw aNullPointerException. - An empty map. With no entries, the loop body never runs and the program prints nothing.
- Typing the grade type.
var gradewithout: Stringand without a value doesn't compile, because Kotlin can't infer a type from nothing.
Testing
| Data | Output |
|---|---|
| Math 92, English 78, Science 85, History 67 | English: C, History: D, Math: A, Science: B (one per line) |
| math 91, Zoology 55, Art 60, art 59 | Art: D, Zoology: F, art: F, math: A (one per line) |
| (no entries) | no output |
