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()andcompute();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
- Create a dictionary (Map). The most common implementation is
HashMap. Example:Map<String, Integer> scores = new HashMap<>(); - Add initial entries (optional). Use
put()to populate:scores.put("Alice", 90); - Update an existing key with
put(). Simply callput()with the same key and a new value. This overwrites the old value. Example:scores.put("Alice", 95);Now Alice’s score is 95. - 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. - 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. - 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. - Use
replace(key, oldValue, newValue)for conditional update. This updates only if the current value matchesoldValue. Example:scores.replace("Alice", 95, 98);This changes Alice’s score to 98 only if it is currently 95. - 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). - 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. - 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. - 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. - Remove a key if needed (not an update, but often related). Use
remove(key)orremove(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. UseputIfAbsent()orcomputeIfAbsent()to avoid clobbering. - Forgetting that
replace()does nothing if the key is missing. Many expect it to add the key, but it doesn’t. Useput()for that. - Null values in
compute(). If a key maps tonull,compute()treats it as absent. The lambda receivesnullas the value, and if the lambda returnsnull, 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 callput()to update, you’ll get aConcurrentModificationException(unless you usereplace()orsetValue()).
Tips
- Choose the right method for clarity: Use
put()for simple overwrites,putIfAbsent()for defaults,replace()for conditional updates,merge()for accumulating values, andcompute()for complex logic. - Use
Map.Entry.setValue()when iterating. If you’re already inside a loop overentrySet(), callingentry.setValue(newValue)is safe and efficient. - Consider
TreeMapif 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);thenmap.put(key, old + 1); - For thread safety, use
ConcurrentHashMap. Itsput(),merge(), andcompute()are atomic, butreplace()may require a loop.
Troubleshooting
- Update doesn’t happen. Check if you used
replace()with a key that doesn’t exist. If so, switch toput()ormerge(). - 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()orcompute(). The remapping function might returnnull, 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 isnull. Check your lambda for null handling. - Using
put()inside a loop overkeySet()and getting weird results. Iterating overkeySet()and callingput()can cause the set to change, leading to missed keys. UseentrySet()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
- View Sent Emails in QuickBooks: Full Guide
- Trade Balance: How It’s Calculated and Read
- How Much Does Coding Cost? Real Prices for 2025
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets Merge Cells: Do They Keep All Values?No—Google Sheets keeps only the value in the upper-left cell when you merge a range; content in the…
- Freeze Panes in Excel: Keep Rows and Columns VisibleTo freeze panes in Excel for Microsoft 365 on Windows, select the cell just below the rows and…
- How to Get Out of Track Changes Mode in Microsoft WordTo get out of Track Changes mode in Word, open the Review tab and turn off Track Changes.…
- How to Change the View in Microsoft Outlook DesktopTo change the view in Outlook desktop, open the folder or calendar you want to adjust, select the…
- Excel Data Validation List With a Blank OptionTo add a blank choice to an Excel drop-down, include a genuinely empty cell in the list’s source…
- How to Create a Color Key in Excel for Clearer DataTo create a color key in Excel, add a small legend beside or below your data, assign each…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.