Start learning free

LESSON 230 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Arrays to a Dictionary in Scala: Pairing by Index

Practice Read the full explanation

Given an array of strings names and an array of integers scores of the same length, pair each name with the score at the same index. Return a mutable.Map where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty mutable.Map. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Scala, explained

    Problem overview

    The method toDictionary receives an Array[String] of names and an Array[Int] of scores with the same length. It returns a scala.collection.mutable.Map[String, Int] where each name is a key and the score at the same index is its value. Names are all different, two names may share a score, and empty arrays give an empty map.

    For Array("Ana", "Ben", "Cara") and Array(90, 75, 88), the map has Ana mapped to 90, Ben to 75 and Cara to 88. For Array("Zoe", "Adam") and Array(60, 60), there are two entries, both with the value 60: equal values are fine, only keys must be unique.

    Approach

    The two arrays are linked by position: names(i) belongs with scores(i). So the loop runs over the indices rather than over the elements, and each pass uses one index to reach both arrays. Each pass adds one entry to a mutable map.

    This pairing pattern comes up whenever data arrives as parallel lists, such as a column of names next to a column of numbers. The map makes the link explicit: after the loop you ask for a name and get its score, without remembering the position.

    Step by step

    1. Create the result. scala.collection.mutable.Map[String, Int]() in a val named result: empty, and changeable.
    2. Loop over the indices. for (i <- 0 until names.length) visits 0, 1, 2 and so on up to one less than the length. The range 0 until 3 holds 0, 1 and 2; 0 until 0 is empty, so empty input does nothing.
    3. Store the pair. result(names(i)) = scores(i) adds the key names(i) with the value scores(i).
    4. Return result.

    The solution in Scala

    class Solution {
        def toDictionary(names: Array[String], scores: Array[Int]): scala.collection.mutable.Map[String, Int] = {
            val result = scala.collection.mutable.Map[String, Int]()
            for (i <- 0 until names.length) {
                result(names(i)) = scores(i)
            }
            return result
        }
    }
    
    • Two sets of parentheses. In result(names(i)) = scores(i), the inner names(i) reads an array element and the outer result(...) is the map's key. Writing to a key that isn't there adds it, and writing to one that is there replaces its value.
    • until versus to. 0 until n stops before n. 0 to n includes n, which would read one element past the end of the arrays and throw an ArrayIndexOutOfBoundsException.
    • Mutable map type. The result is changed as the loop runs, so it has to be scala.collection.mutable.Map, not the default immutable Map.
    • A library shortcut. names.zip(scores) pairs the two arrays into (name, score) tuples, and scala.collection.mutable.Map.from(names.zip(scores)) builds a mutable map from them. The loop above does the same job and shows each step.

    Edge cases and common mistakes

    • Empty arrays. The range 0 until 0 has no indices, so the loop never runs and the method returns HashMap().
    • Repeated names. The lesson promises distinct names. If a name did repeat, the later score would replace the earlier one: with names Array("Ana", "Ana") and scores Array(1, 2) the map ends up as HashMap(Ana -> 2).
    • Looping over the values. With for (name <- names) there is no index to find the matching score. Use the index range.
    • Different lengths. If scores were shorter than names, the loop would throw when it ran off the end of scores. The lesson guarantees equal lengths.

    Testing

    • Array("Ana", "Ben", "Cara"), Array(90, 75, 88) gives HashMap(Cara -> 88, Ana -> 90, Ben -> 75).
    • Array("Zoe", "Adam"), Array(60, 60) gives HashMap(Adam -> 60, Zoe -> 60).
    • Array("Max"), Array(100) gives HashMap(Max -> 100).
    • Two empty arrays give HashMap().
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free