How to Update a Dictionary in Java (HashMap)

How-to basics · Updated November 22, 2026

In Java, a “dictionary” is typically a HashMap (or another Map implementation like TreeMap or LinkedHashMap). Updating a dictionary means changing the value associated with an existing key, or adding a new key-value pair if the key doesn’t exist. The core method is put(), but Java 8+ offers merge(), compute(), and replace() for more control. This guide covers all common update scenarios with clear code examples.

What You’ll Need

  • Java Development Kit (JDK) 8 or later (for merge() and compute(); put() works in all versions)
  • Any IDE or text editor (Eclipse, IntelliJ, VS Code, or even Notepad)
  • Basic understanding of Java syntax and generics

Step-by-Step

  1. Create a dictionary (Map). The most common implementation is HashMap. Example: Map<String, Integer> scores = new HashMap<>();
  2. Add initial entries (optional). Use put() to populate: scores.put("Alice", 90);
  3. Update an existing key with put(). Simply call put() with the same key and a new value. This overwrites the old value. Example: scores.put("Alice", 95); Now Alice’s score is 95.
  4. Add a new key with put(). If the key doesn’t exist, put() adds it. Example: scores.put("Bob", 80); This adds Bob if not present, or updates if present.
  5. Use putIfAbsent() to add only if key is missing. This avoids overwriting an existing value. Example: scores.putIfAbsent("Charlie", 75); If Charlie exists, his value stays.
  6. Use replace() to update only if key exists. This does nothing if the key is missing. Example: scores.replace("Alice", 100); If Alice exists, her score becomes 100; if not, no change.
  7. Use replace(key, oldValue, newValue) for conditional update. This updates only if the current value matches oldValue. Example: scores.replace("Alice", 95, 98); This changes Alice’s score to 98 only if it is currently 95.
  8. Use merge() to combine a new value with an existing one. This is perfect for counters or accumulations. Example: scores.merge("Alice", 5, Integer::sum); This adds 5 to Alice’s current score (or sets to 5 if Alice doesn’t exist).
  9. Use compute() to update based on the current value. The lambda receives the key and current value (or null if absent). Example: scores.compute("Alice", (k, v) -> v == null ? 1 : v + 1); This increments Alice’s score by 1, or sets to 1 if missing.
  10. Use computeIfAbsent() to compute a value only if key is absent. Example: scores.computeIfAbsent("David", k -> 70); Adds David with 70 if he’s not there.
  11. Use computeIfPresent() to recompute only if key exists. Example: scores.computeIfPresent("Alice", (k, v) -> v + 10); Adds 10 to Alice if she exists; does nothing otherwise.
  12. Remove a key if needed (not an update, but often related). Use remove(key) or remove(key, value) to delete only if the current value matches.

Common Mistakes

  • Using put() when you want to preserve the old value. put() always overwrites. Use putIfAbsent() or computeIfAbsent() to avoid clobbering.
  • Forgetting that replace() does nothing if the key is missing. Many expect it to add the key, but it doesn’t. Use put() for that.
  • Null values in compute(). If a key maps to null, compute() treats it as absent. The lambda receives null as the value, and if the lambda returns null, the key is removed. Be careful.
  • Using merge() incorrectly with non-associative functions. For example, using subtraction ((a, b) -> a - b) can produce different results depending on order. Use commutative/associative operations like sum or max.
  • Modifying the map while iterating. If you iterate over entrySet() and call put() to update, you’ll get a ConcurrentModificationException (unless you use replace() or setValue()).

Tips

  • Choose the right method for clarity: Use put() for simple overwrites, putIfAbsent() for defaults, replace() for conditional updates, merge() for accumulating values, and compute() for complex logic.
  • Use Map.Entry.setValue() when iterating. If you’re already inside a loop over entrySet(), calling entry.setValue(newValue) is safe and efficient.
  • Consider TreeMap if you need sorted keys. Updates work the same way, but iteration is in natural order.
  • Use getOrDefault() for safe reads before updating. Example: int old = map.getOrDefault(key, 0); then map.put(key, old + 1);
  • For thread safety, use ConcurrentHashMap. Its put(), merge(), and compute() are atomic, but replace() may require a loop.

Troubleshooting

  • Update doesn’t happen. Check if you used replace() with a key that doesn’t exist. If so, switch to put() or merge().
  • ConcurrentModificationException. You’re modifying the map while iterating. Use entry.setValue() inside the loop, or collect changes and apply after the loop.
  • NullPointerException in merge() or compute(). The remapping function might return null, which removes the key. Ensure your function returns a non-null value, or handle null explicitly.
  • Values not updating as expected with compute(). Remember that if the key is absent, the value passed to the lambda is null. Check your lambda for null handling.
  • Using put() inside a loop over keySet() and getting weird results. Iterating over keySet() and calling put() can cause the set to change, leading to missed keys. Use entrySet() instead.

Frequently Asked Questions

What is the difference between put() and replace()?

put() always sets the value, adding the key if it doesn’t exist. replace() only updates if the key exists; it does nothing otherwise.

How do I increment an integer value in a HashMap?

Use map.merge(key, 1, Integer::sum) or map.compute(key, (k, v) -> (v == null) ? 1 : v + 1).

Can I update a key’s value while iterating over the map?

Yes, but avoid structural modifications. Use entry.setValue(newValue) inside the loop, or collect updates and apply after iteration.

What happens if I use put() with a null key?

For HashMap, null keys are allowed. For TreeMap, null keys are not allowed and throw a NullPointerException.

How do I update a value only if the new value is greater than the old?

Use merge() with a custom remapping function: map.merge(key, newVal, (old, new) -> old > new ? old : new).

Is there a way to update multiple keys at once?

No built-in method for multiple updates, but you can loop through a collection of keys and call put() or replace() for each.

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.