How to update the value of a key in HashMap is introduced.
1. Update value for key
You can update the value for a previously registered key with put(key, value)
as shown below.
If key does not exist in HashMap, key and value are added to HashMap.
import java.util.HashMap;
import java.util.Map;
public class UpdateValueOfHashMap {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
// update
map.put("melon", 10);
System.out.println("Result: " + map);
}
}
Output:
Result: {apple=1, kiwi=3, melon=10}
2. Increment value for key
When value is an Integer type, value can be increased by a certain amount.
The code below is an example of updating the value stored in a specific key by adding 20.
import java.util.HashMap;
import java.util.Map;
public class UpdateValueOfHashMap2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
map.put("melon", map.get("melon") + 20);
System.out.println("Result: " + map);
}
}
Output:
Result: {apple=1, kiwi=3, melon=22}
NullPointerException
However, if the value for the key does not exist as follows, get()
returns null and a NullPointerException occurs.
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
map.put("banana", map.get("banana") + 20);
Output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
at UpdateValueOfHashMap2.main(UpdateValueOfHashMap2.java:14)
3. Increment value only when key exists
Using containsKey(key)
and the ternary operator, you can increase the value only if the key exists.
This implementation avoids NullPointerException.
The code below is an example of incrementing 20 if key exists, and setting it to 1 otherwise.
import java.util.HashMap;
import java.util.Map;
public class UpdateValueOfHashMap2_1 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
map.put("apple", map.containsKey("apple") ? map.get("apple") + 20 : 1);
map.put("banana", map.containsKey("banana") ? map.get("banana") + 20 : 1);
System.out.println("Result: " + map);
}
}
Output:
Result: {banana=1, apple=21, kiwi=3, melon=2}
4. compute()
By using compute()
, the value can be incremented only when the key exists.
compute()
takes BiFunction as an argument as shown below, and can be implemented with simpler code than the example above.
import java.util.HashMap;
import java.util.Map;
public class UpdateValueOfHashMap4 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
map.compute("apple", (k, v) -> (v == null) ? 1 : v + 20);
map.compute("banana", (k, v) -> (v == null) ? 1 : v + 1);
System.out.println("Result: " + map);
}
}
Output:
Result: {banana=1, apple=21, kiwi=3, melon=2}
5. getOrDefault()
getOrDefault(key, default)
returns the value for the key, or default if the key does not exist.
Using getOrDefault()
will not throw NullPointerException.
import java.util.HashMap;
import java.util.Map;
public class UpdateValueOfHashMap3 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("melon", 2);
map.put("kiwi", 3);
map.put("melon", map.getOrDefault("melon", 0) + 10);
map.put("banana", map.getOrDefault("banana", 0) + 10);
System.out.println("Result: " + map);
}
}
Output:
Result: {banana=10, apple=1, kiwi=3, melon=12}
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)