Skip to content

Map & Key Lookup

The Course
•
15 min study

A Map associates a unique key with a value. A task ID can select one task without scanning every entry. A map is not a list of positions: get("A1") looks up an ID, not index A1. LinkedHashMap keeps keys in insertion order for predictable reports.

Work through the example

put inserts or replaces a mapping. It does not reject duplicate keys automatically. Decide whether replacement is intended before choosing an insertion method. containsKey distinguishes absence from a present mapping. This course avoids storing null values, so a null result from get means the key is missing.

Map<String, Integer> supplies two type arguments: key and value. getOrDefault(key, 0) returns zero for an absent key without creating an entry. Assign the updated total with put. The boxed Integer is converted to int for addition. This is a counting pattern, not an invitation to store unrelated meanings under one key.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> totals = new LinkedHashMap<>();
        for (String topic : new String[] {"Java", "Tests", "Java"}) {
            int previous = totals.getOrDefault(topic, 0);
            totals.put(topic, previous + 1);
        }
        System.out.println(totals);
        System.out.println(totals.containsKey("Missing"));
    }
}
Check your prediction
Text
{Java=2, Tests=1}
false

Compare the behavior

Replacement keeps the original key position in this LinkedHashMap. In a task store, an accidental replacement could lose a task. Guard insertion when duplicates should be invalid. Later we will place that rule inside a repository class so callers cannot bypass it.

Trace the changed case Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        Map<String, String> tasks = new LinkedHashMap<>();
        tasks.put("A1", "Read");
        boolean duplicate = tasks.containsKey("A1");
        if (!duplicate) {
            tasks.put("A1", "Overwrite");
        }
        System.out.println(duplicate);
        System.out.println(tasks.get("A1"));
    }
}
Check your prediction
Text
true
Read

Choose the structure by the question

QuestionStructureExample
What happened, in sequence, including repeats?ListRead, Test, Read
Which distinct values occurred?SetRead, Test
What value belongs to this key?MapA1 maps to Read

These are different questions about the same application. A map's keys are unique, but different keys can have equal values: A1 and B2 may both map to Read. A set is not a shortcut for counting repeated events, because it discards the counts.

Trace the mapping after every update

A map's key is unique, but its values need not be. A1 → Read and B2 → Read are two different mappings. Repeating put(A1, Test) changes A1's value; it does not add a second A1. This is why duplicate rejection must be explicit when replacing a task would lose important data.

For counting, write a trace row for each incoming word. On Java, Tests, Java, the first Java sees a default zero and stores one; Tests starts another key; the last Java reads one and stores two. The keys' first-seen positions remain stable in LinkedHashMap. The count changes, not the key's identity.

With a no-null-values contract, get returning null can represent absence. A map allowing null values would need containsKey to distinguish absent from present-with-null. Keep today's simpler policy explicit so a missing lookup cannot accidentally be unboxed into an int.

Practice independently

Exercise

Map & Key Lookup: practice

For a nonnull array of nonnull strings, build counts(String[] words) returning a LinkedHashMap of exact word counts. Preserve first-key order. Empty input returns an empty map. For {"a", "b", "a"} print {a=2, b=1}. Do not count a repeated key as a new distinct word.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println("Implement counts");
    }
}
Hint 1: the idea

A repeated key updates its existing value. A default of zero handles the first occurrence.

Hint 2: a first step

Read the previous count into an int, then put previous plus one under the same word.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
import java.util.Map;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println(counts(new String[] {"a", "b", "a"}));
        System.out.println(counts(new String[0]));
    }

    static Map<String, Integer> counts(String[] words) {
        Map<String, Integer> result = new LinkedHashMap<>();
        for (String word : words) {
            int previous = result.getOrDefault(word, 0);
            result.put(word, previous + 1);
        }
        return result;
    }
}

Expected output:

Text
{a=2, b=1}
{}

Change it and test again

Try all-equal words, all-distinct words and words differing by case. Replace previous + 1 with 1: which test detects the defect? Explain why containsKey alone cannot tell you how many times a key appeared.

Explain before moving on

How does a map differ from a set? If duplicate task IDs must be rejected, where should that policy live so every caller gets the same behavior?

Was this article helpful?

Your response is saved on this device.