Start learning free

LESSON 98 OF 344 · DICTIONARIES

Dictionaries in Java: Creating a HashMap with put

Lesson Read the full explanation

In Java, a HashMap works like a dictionary — it stores key-value pairs where each key maps to a value. You need to import java.util.HashMap.

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);

The type parameters <String, Integer> specify the key type and value type. Use put(key, value) to add entries:

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice"));  // 25
System.out.println(ages.size());        // 2

Assignment
Follow the Coding Tutorial and create a HashMap named scores with three student scores!


Hint
Declare HashMap<String, Integer> scores = new HashMap<>() then use put() to add entries.

STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · DICTIONARIES

    Dictionaries in Java, explained

    What a dictionary is

    A dictionary stores key-value pairs. You look something up by its key and get back the value stored with it, the way you find a phone number by looking up a name. Other languages give this structure its own syntax. In Java it is a class from the standard library, and the most common one is HashMap.

    Use a HashMap whenever you need to find a value by a label instead of by position: scores by student name, prices by product code, counts by word. Each key appears at most once, while different keys may hold equal values.

    Creating a HashMap

    The class lives in the java.util package, so a full program starts with import java.util.HashMap; (or import java.util.*;). Then you declare the map and create it with new:

    HashMap<String, Integer> scores = new HashMap<>();
    

    Read it from the left:

    • HashMap<String, Integer> is the type. The two names in angle brackets are the key type and the value type, so this map uses String keys and Integer values.
    • scores is the variable name.
    • new HashMap<>() creates an empty map. The empty angle brackets are called the diamond. Java fills in the types from the declaration on the left, so you don't have to write them twice.

    The type arguments must be object types, which is why the value type is Integer and not int. Integer is the wrapper class for int. Java converts between the two automatically, so you can write put("Alice", 95) with a plain number. The other wrappers follow the same pattern: Double, Boolean and Character.

    Adding entries with put

    The put(key, value) method adds an entry:

    HashMap<String, Integer> ages = new HashMap<>();
    ages.put("Alice", 25);
    ages.put("Bob", 30);
    System.out.println(ages.get("Alice"));   // 25
    System.out.println(ages.size());         // 2
    

    get(key) returns the value for a key, and size() returns the number of entries. If you call put with a key that is already in the map, the old value is replaced instead of a second entry being added. So the map never holds two entries with the same key.

    The lesson's exercise

    The task is to build a map named scores with three students. It has two steps:

    1. Create the map. Declare scores as a HashMap<String, Integer> and initialize it with new HashMap<>(). The map starts empty.
    2. Add the three entries. Call put once per student: "Alice" with 95, "Bob" with 87 and "Charlie" with 72.

    The complete code is:

    HashMap<String, Integer> scores = new HashMap<>();
    scores.put("Alice", 95);
    scores.put("Bob", 87);
    scores.put("Charlie", 72);
    

    Afterwards the map holds three entries, and scores.get("Bob") is 87.

    Good to know

    • The order is not guaranteed. A HashMap doesn't remember the order you inserted entries in, and printing it or looping over its keys can list them in an order that looks random. Never rely on that order. If you need insertion order, use LinkedHashMap, and for keys in sorted order, TreeMap.
    • Keys are compared with equals. "Alice" and "alice" are different keys, so the capitalization you use in put must match later in get.
    • Keys can be other types. A HashMap<Integer, String> maps numbers to text: after byId.put(7, "Ann"), byId.get(7) gives "Ann".
    • Declaring with the interface is common. Map<String, Integer> scores = new HashMap<>(); works the same way for the methods in this chapter and lets you swap the implementation later. This lesson uses HashMap as the declared type.
    • Forgetting the import is a compile error. Without java.util.HashMap imported, the compiler reports that it cannot find the symbol HashMap.

    Key takeaways

    • A HashMap<K, V> stores unique keys of type K, each with a value of type V.
    • Create one with new HashMap<>() and fill it with put(key, value).
    • The type arguments must be object types, such as Integer instead of int.
    • A repeated key replaces the old value, and the iteration order is unspecified.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free