⚡IntermediateCollections Framework

HashMap

Store key-value pairs with HashMap for fast lookup, insertion, and deletion by key.

Overview

HashMap stores data as key-value pairs (like a dictionary). Given a key, you can retrieve its value in O(1) average time. Keys must be unique; if you put a duplicate key, the old value is replaced. Values can repeat. HashMap does not guarantee any ordering of keys. If you need keys sorted, use TreeMap. If you need insertion order, use LinkedHashMap. Common use cases: counting frequencies, caching computed values, grouping items by a property, and looking up records by an ID.

Key Points

  • •Import java.util.HashMap and java.util.Map
  • •Declare as Map<K, V> map = new HashMap<>() for flexibility
  • •put(key, value) adds or replaces; get(key) retrieves (null if absent)
  • •containsKey(key) and containsValue(value) for existence checks
  • •remove(key) deletes an entry; size() gives the count
  • •getOrDefault(key, defaultValue) avoids null checks
  • •putIfAbsent(key, value) only inserts if key is not already present
  • •Iterate with entrySet(), keySet(), or values()

Examples

Basic HashMap operations

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 28);
        ages.put("Bob", 34);
        ages.put("Carol", 25);

        System.out.println("Bob's age: " + ages.get("Bob")); // 34
        System.out.println("Has Dave: " + ages.containsKey("Dave")); // false

        // getOrDefault avoids null
        int age = ages.getOrDefault("Dave", 0);
        System.out.println("Dave's age: " + age); // 0

        ages.put("Bob", 35); // replaces old value
        ages.remove("Carol");

        System.out.println(ages); // {Alice=28, Bob=35}
        System.out.println("Size: " + ages.size());
    }
}

get() returns null for missing keys. Always use getOrDefault or containsKey before using the result.

Iterating over a HashMap

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Double> prices = new HashMap<>();
        prices.put("Apple", 1.20);
        prices.put("Banana", 0.50);
        prices.put("Cherry", 3.00);

        // Iterate entries (key + value)
        for (Map.Entry<String, Double> entry : prices.entrySet()) {
            System.out.printf("%s: $%.2f%n", entry.getKey(), entry.getValue());
        }

        // Iterate keys only
        for (String fruit : prices.keySet()) {
            System.out.println(fruit);
        }

        // Iterate values only
        double total = 0;
        for (double price : prices.values()) total += price;
        System.out.printf("Total: $%.2f%n", total);
    }
}

entrySet() is the most efficient way to iterate both key and value. keySet() and values() are convenient for single-sided needs.

Counting word frequencies

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String sentence = "the cat sat on the mat the cat";
        String[] words = sentence.split(" ");

        Map<String, Integer> freq = new HashMap<>();
        for (String word : words) {
            freq.put(word, freq.getOrDefault(word, 0) + 1);
        }

        for (Map.Entry<String, Integer> e : freq.entrySet()) {
            System.out.println(e.getKey() + ": " + e.getValue());
        }
        // the: 3, cat: 2, sat: 1, on: 1, mat: 1
    }
}

getOrDefault(word, 0) + 1 is the standard idiom for counting. Java 8 also offers merge(key, 1, Integer::sum).

Common Mistakes

  • Using == to compare String keys instead of equals(). HashMap uses equals() and hashCode() internally, but comparing the retrieved value with == can fail for non-identical objects
  • Assuming HashMap maintains insertion order. It does not. Use LinkedHashMap if order matters
  • Ignoring null returns from get(). Always check or use getOrDefault to avoid NullPointerException when unboxing

Note

For frequency counting, the idiom map.merge(key, 1, Integer::sum) is cleaner than getOrDefault. It adds 1 if the key exists, or puts 1 if it is absent.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What happens if you call put() with a key that already exists in a HashMap?