Start learning free

LESSON 226 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Two Lists to a Dictionary in Java: Pairing Arrays into a HashMap

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 HashMap 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 HashMap. 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

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Two Lists To A Dictionary in Java, explained

    Problem overview

    The method toDictionary receives an array of strings, names, and an array of integers, scores, of the same length. It returns a HashMap<String, Integer> in which each names[i] is a key and scores[i] is its value.

    For ["Ana", "Ben", "Cara"] and [90, 75, 88] the map is {Cara=88, Ana=90, Ben=75}: "Ana" sits at index 0 and so does 90, and the same goes for the other two. The names are all different, but two names may share a score, so ["Zoe", "Adam"] with [60, 60] gives two entries, {Adam=60, Zoe=60}. Two empty arrays give an empty map, {}. The order of the entries doesn't matter, and the order you see when printing is chosen by the HashMap.

    Approach: one index reaches both arrays

    The arrays are parallel: position i in one belongs with position i in the other. A single loop over the indices can therefore read both values and store them as one entry. The loop runs once per name, and each pass adds exactly one entry.

    Step by step

    1. Create the empty map. HashMap<String, Integer> result = new HashMap<>(); will get one entry per name.
    2. Loop over the indices. You need the index itself, so the enhanced for loop isn't enough here. Use for (int i = 0; i < names.length; i++). Arrays use the field length, without parentheses.
    3. Store the pair. result.put(names[i], scores[i]) uses the name as the key and the score at the same index as the value. The int is boxed into an Integer automatically.
    4. Return the map after the loop.

    The solution in Java

    class Solution {
        public HashMap<String, Integer> toDictionary(String[] names, int[] scores) {
            HashMap<String, Integer> result = new HashMap<>();
            for (int i = 0; i < names.length; i++) {
                result.put(names[i], scores[i]);
            }
            return result;
        }
    }
    

    Java details worth knowing:

    • Empty input. With two empty arrays the loop condition 0 < 0 is false at once, so the method returns an empty map with no special case.
    • put replaces. If a key is stored twice, the later value overwrites the earlier one and the map keeps one entry. With names that are all different, as promised, that can't happen. With ["Ana", "Ana"] and [1, 2] the result would be {Ana=2}.
    • Two arrays, two lengths. The loop uses names.length. If scores were shorter, scores[i] would throw an ArrayIndexOutOfBoundsException. The lesson guarantees equal lengths.
    • The printed form. A map prints as {key=value, ...} with no quotes around the strings, in an order the HashMap decides.

    What the map is for

    The two arrays can only be matched by position, so finding Ben's score means searching the names for "Ben" and then reading the same index in scores. The map removes that step. For the first example, get("Ben") is 75, containsKey("Cara") is true, size() is 3, and get("Dan") is null, because "Dan" was never added.

    Complexity

    Time: O(n) for n names, since each put costs a constant amount on average. Space: O(n), because the map holds one entry per name.

    Edge cases and common mistakes

    • Looping with names.length(). That doesn't compile: arrays have a length field, not a method.
    • Swapping key and value. result.put(scores[i], names[i]) would not match the return type, and scores can repeat, so entries would be lost.
    • Returning inside the loop. The map would hold only the first pair.
    • Expecting the map to keep the input order. A HashMap doesn't. Use a LinkedHashMap if you need the order of insertion.

    Testing

    • ["Ana", "Ben", "Cara"] and [90, 75, 88] give {Cara=88, Ana=90, Ben=75}.
    • ["Zoe", "Adam"] and [60, 60] give {Adam=60, Zoe=60}.
    • ["Max"] and [100] give {Max=100}.
    • Two empty arrays give {}.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free