Java - Update the value of a key in HashMap

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}
codechachaCopyright ©2019 codechacha