How to Use a Dictionary in Java (HashMap)

How-to basics · Updated November 23, 2026

In Java, a “dictionary” is most commonly implemented using the HashMap class, which stores key-value pairs. This guide shows you how to create, populate, access, and iterate over a dictionary using HashMap, plus how to handle common pitfalls. You’ll need a basic understanding of Java syntax and a development environment (like JDK and an IDE or text editor) to follow along.

What You’ll Need

  • Java Development Kit (JDK) 8 or later installed.
  • A text editor or IDE (e.g., IntelliJ IDEA, Eclipse, VS Code).
  • Basic familiarity with Java classes and methods.

Step-by-Step

  1. Import the HashMap class. At the top of your Java file, add import java.util.HashMap; (and import java.util.Map; if you plan to use the Map interface). This makes the class available.
  2. Declare and instantiate the dictionary. Choose the key and value types. For example, to map String keys to Integer values:
    Map<String, Integer> dictionary = new HashMap<>();
    Using the Map interface is a good practice because it allows you to swap implementations later.
  3. Add key-value pairs. Use the put method:
    dictionary.put("apple", 3);
    dictionary.put("banana", 5);
    If the key already exists, put replaces the old value and returns the previous value (or null if new).
  4. Retrieve a value by key. Use get:
    Integer count = dictionary.get("apple");
    This returns null if the key is not present. To avoid null, check with containsKey first or use getOrDefault.
  5. Check if a key or value exists. Use containsKey and containsValue:
    if (dictionary.containsKey("banana")) { ... }
    boolean hasValue = dictionary.containsValue(5);
  6. Remove an entry. Use remove:
    dictionary.remove("apple");
    This returns the removed value, or null if the key wasn’t there.
  7. Iterate over the dictionary. Use a for-each loop over entrySet() to get both keys and values:
    for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
      System.out.println(entry.getKey() + " -> " + entry.getValue());
    }
    Alternatively, iterate over keySet() or values() if you only need one side.
  8. Get the size. Use size() to see how many entries are stored:
    int total = dictionary.size();
  9. Clear all entries. Use clear() to empty the dictionary:
    dictionary.clear();
  10. Use default values (optional). To avoid null checks, use getOrDefault:
    Integer count = dictionary.getOrDefault("orange", 0);
    This returns 0 if “orange” is not a key.

Common Mistakes

  • Forgetting to import java.util.HashMap – causes a compilation error.
  • Using primitive types like int instead of wrapper classes Integer in generics – HashMap cannot store primitives.
  • Assuming insertion order – HashMap does not guarantee order. Use LinkedHashMap if you need insertion order, or TreeMap for sorted order.
  • Modifying the dictionary while iterating (adding or removing entries) can throw ConcurrentModificationException unless you use an iterator’s remove() method.
  • Using mutable objects as keys – if the key’s hash code changes after insertion, the entry becomes unreachable.

Tips

  • Use Map<K, V> as the variable type for flexibility – you can switch to TreeMap or LinkedHashMap without changing the rest of the code.
  • Use getOrDefault to provide fallback values and avoid null checks.
  • When performance matters, initialize with an expected capacity: new HashMap<>(expectedSize) to reduce resizing overhead.
  • For thread-safe operations, use ConcurrentHashMap instead of HashMap.
  • Override equals() and hashCode() in custom key classes to ensure correct behavior.

Troubleshooting

  • Compilation error: “cannot find symbol” – Check the import statement and that you’re using the correct class name (HashMap).
  • NullPointerException when calling get – The key might not exist, so get returns null. Use containsKey or getOrDefault to handle it.
  • ConcurrentModificationException – You’re modifying the map while iterating. Use an iterator and call iterator.remove(), or collect keys to remove and delete after the loop.
  • Unexpected order of entries – Remember HashMap is unordered. If order matters, switch to LinkedHashMap (insertion order) or TreeMap (sorted by key).
  • Keys with same hash code – This is normal; HashMap handles collisions using equals(). Ensure your key’s equals() is consistent with hashCode().

Frequently Asked Questions

  1. What is the difference between HashMap and Hashtable?
    Hashtable is synchronized (thread-safe) and does not allow null keys or values. HashMap is not synchronized and allows one null key and multiple null values. In modern code, prefer ConcurrentHashMap for thread safety.
  2. Can I use a custom object as a key?
    Yes, but you must override equals() and hashCode() so that equal objects produce the same hash code. Otherwise, lookups may fail.
  3. How do I iterate over a HashMap in Java 8+?
    You can use a for-each loop on entrySet(), or use the forEach method with a lambda: dictionary.forEach((key, value) -> System.out.println(key + " -> " + value));
  4. Is HashMap ordered?
    No, HashMap does not maintain any order. If you need insertion order, use LinkedHashMap. For sorted order by key, use TreeMap.
  5. What happens if I put a duplicate key?
    The old value is replaced with the new one, and put returns the previous value (or null if it was new).
  6. How can I make a dictionary thread-safe?
    Use ConcurrentHashMap from java.util.concurrent. It provides thread-safe operations without locking the entire map.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.