Start learning free

LESSON 205 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Report Card V5 in Kotlin: Grades from a TreeMap in Alphabetical Order

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:

val grades = java.util.TreeMap<String, Int>()
grades["Math"] = 92
grades["English"] = 78
grades["Science"] = 85
grades["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.

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)
}

STEP 1 OF 9
    Ctrl + Enter to check

    KOTLIN · PROJECTS: EVERYDAY PROGRAMS

    Report Card V5 in Kotlin, explained

    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

    1. 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.
    2. Look up the score. grades[subject] returns the value stored under that key. In Kotlin a lookup in a map has the type Int?, because the key might be missing. Ending with !! tells the compiler that this key is certainly there, and gives a plain Int.
    3. Declare the grade. var grade: String with no value yet. The type has to be written because nothing is assigned.
    4. Build the ladder. if (score >= 90) gives "A", then else if tests for 80, 70 and 60 give "B", "C" and "D", and a plain else gives "F". As before, each test relies on the previous ones having failed.
    5. 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 TreeMap directly. The lesson writes the full name java.util.TreeMap instead of importing it. Kotlin also has its own sortedMapOf function, but the lesson uses the class.
    • Index syntax on a map. grades["Math"] = 92 calls put, and grades[subject] calls get. Assigning to an existing key replaces its value, so the map never holds a key twice.
    • What !! does. It converts Int? to Int and throws a NullPointerException if the value is null. Here the keys come from the map itself, so the lookup can't fail. Writing grades["Art"] for a subject that isn't in the map gives null, and adding !! to that lookup would throw.
    • Why a plain HashMap isn't enough. A HashMap promises 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. The TreeMap gives [English, History, Math, Science].
    • var versus val for grade. The lesson declares var grade: String. Each pass assigns it once, so val would 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:

    subjectscoreFirst test that is truePrinted
    English78score >= 70English: C
    History67score >= 60History: D
    Math92score >= 90Math: A
    Science85score >= 80Science: 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, Art and art, the loop visits Art, Zoology, art and then math. The lesson's names all start with a capital letter, so it doesn't show up here.
    • Printing in the wrong place. A println after the loop would run once, and grade would be out of scope there.
    • Duplicate keys. Setting grades["Math"] = 50 a 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"], gives null. Printing it shows null, and adding !! makes it throw a NullPointerException.
    • An empty map. With no entries, the loop body never runs and the program prints nothing.
    • Typing the grade type. var grade without : String and without a value doesn't compile, because Kotlin can't infer a type from nothing.

    Testing

    DataOutput
    Math 92, English 78, Science 85, History 67English: C, History: D, Math: A, Science: B (one per line)
    math 91, Zoology 55, Art 60, art 59Art: D, Zoology: F, art: F, math: A (one per line)
    (no entries)no output
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free