Intermediate 8 min

Maps and sets

A map looks up a value by key, and a set records whether a value is present.

How it works

Start with the question you need to answer. If you only ask whether an order ID was already seen, keep it in a set. If you ask how many times that ID occurred, use the ID as a map key and store a count. Keep the key itself stable after insertion.

Walk through an example

Use a HashSet to keep track of IDs you have seen. Use a HashMap from ID to count if you also need how often each ID appeared.

What to watch for

Hash-based structures do not promise iteration order. Mutating the fields used by a key’s hash code after insertion can break lookups.

Code example

public class Main {
    public static void main(String[] args) {
        java.util.Map<String, Integer> counts = new java.util.HashMap<>();
        counts.put("a", 1);
        counts.put("a", 2);
        System.out.println(counts.get("a"));
    }
}

Check your understanding

Which value does get("a") return?

See the example and explanation
Worked example
Given A map receives put("a", 1) and then put("a", 2).
Answer 2

The second put replaces the previous value for that key.

Open practice problem
Next lessonExceptions and resource handling