How to Make a Dictionary in Java

How-to basics · Updated November 23, 2026

In Java, a dictionary is typically implemented using the Map interface, which stores key-value pairs. The most commonly used implementation is HashMap, which offers fast lookups and insertion. This guide shows you how to create, populate, and use a dictionary in Java, covering both basic and advanced operations.

What You’ll Need

  • Java Development Kit (JDK) 8 or later installed on your system.
  • A text editor or an Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code.
  • Basic understanding of Java syntax and object-oriented concepts.

Step-by-Step

  1. Import the Map and HashMap classes. At the top of your Java file, add:
    import java.util.Map;
    import java.util.HashMap;
  2. Declare and instantiate the dictionary. Use the Map interface as the type and HashMap as the implementation:
    Map<String, Integer> dictionary = new HashMap<>();
    This creates an empty dictionary mapping String keys to Integer values. You can replace the types with any other objects, e.g., Map<String, String>.
  3. Add key-value pairs. Use the put method:
    dictionary.put("apple", 5);
    dictionary.put("banana", 3);
  4. Retrieve a value. Use get with the key:
    int count = dictionary.get("apple");
    If the key doesn’t exist, get returns null (or the default value if using getOrDefault).
  5. Check if a key exists. Use containsKey:
    if (dictionary.containsKey("banana")) { ... }
  6. Remove a key. Use remove:
    dictionary.remove("apple");
  7. Iterate over entries. Use a for-each loop with entrySet():
    for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
      System.out.println(entry.getKey() + " -> " + entry.getValue());
    }
  8. Get the size. Use size():
    int size = dictionary.size();
  9. Update a value. Simply call put again with the same key; it overwrites the old value.
    dictionary.put("banana", 10);
  10. Use other Map methods as needed. For example, keySet() returns all keys, values() returns all values, and clear() empties the dictionary.

Common Mistakes

  • Using Hashtable instead of HashMap. Hashtable is legacy and synchronized; HashMap is preferred for most cases.
  • Assuming insertion order. HashMap does not guarantee order. Use LinkedHashMap for insertion order or TreeMap for sorted order.
  • Forgetting to import Map and HashMap. This causes compilation errors.
  • Using primitive types as generics. You cannot use int, double, etc., directly; use wrapper classes like Integer and Double.
  • Modifying the map while iterating. This throws ConcurrentModificationException. Use Iterator.remove() or collect keys to remove later.

Tips

  • Use getOrDefault to avoid null checks: dictionary.getOrDefault("orange", 0) returns 0 if key not present.
  • Use putIfAbsent to add only if the key is missing: dictionary.putIfAbsent("grape", 2).
  • Prefer Map.of() for immutable dictionaries (Java 9+): Map<String, Integer> immutable = Map.of("a", 1, "b", 2);. Note: Map.of() does not allow null keys or values and has a limit of 10 pairs.
  • Consider ConcurrentHashMap if multiple threads access the dictionary.
  • Use computeIfAbsent to lazily compute values: dictionary.computeIfAbsent("key", k -> expensiveComputation(k)).

Troubleshooting

  • Compilation error: “cannot find symbol” – Ensure you imported java.util.Map and java.util.HashMap.
  • NullPointerException when getting a value – The key may not exist. Use containsKey or getOrDefault to handle missing keys.
  • ClassCastException when retrieving – If you mix types (e.g., put a String where an Integer is expected), the cast fails. Use generics consistently.
  • ConcurrentModificationException – Do not add/remove entries while iterating with for-each. Use Iterator and its remove() method, or iterate over a copy.
  • Unexpected order – HashMap order is not guaranteed. Switch to LinkedHashMap or TreeMap if order matters.
  • OutOfMemoryError – If you add too many entries, ensure your JVM has enough heap. You can increase with -Xmx option.

Frequently Asked Questions

  1. What is the difference between HashMap and Hashtable?
    HashMap is not synchronized and allows one null key and multiple null values. Hashtable is synchronized and does not allow null keys or values. HashMap is generally preferred unless thread safety is required.
  2. Can I use a custom object as a key?
    Yes, but you must override equals() and hashCode() to ensure correct behavior. Otherwise, the map will not find keys correctly.
  3. How do I sort a dictionary by keys or values?
    Use a TreeMap for sorting by keys, or convert the entry set to a list and sort by values using a comparator.
  4. Is there a built-in dictionary class in Java?
    The Dictionary abstract class exists but is obsolete. Use Map implementations instead.
  5. What is the time complexity of HashMap operations?
    On average, put, get, and remove are O(1), assuming a good hash function and proper load factor.
  6. How do I make a dictionary with multiple values per key?
    Use a Map<Key, List<Value>> or Map<Key, Set<Value>> and manage the collection manually.

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.