How do I use replace() and replaceAll() methods of Map?

In Java, the Map interface provides the methods replace() and replaceAll(), which are used to replace existing entries in the map.

Replace:

replace(K key, V value) is a method that replaces the entry for the specified key only if it is currently mapped to some value. It returns the old value associated with the specified key or null if the key is not in the map.

Here is a simple usage of the replace() method:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapReplaceExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "v1");
        map.replace("key1", "value1");

        // Output: New value of key1: value1
        System.out.println("New value of key1: " + map.get("key1"));
    }
}

Output:

New value of key1: value1

replace(K key, V oldValue, V newValue) replaces the entry for the specified key only if currently mapped to the specified value. This variant of replace() method provides additional check for existing value, which can prevent data corruption in concurrent environment without additional synchronization.

ReplaceAll:

replaceAll(BiFunction<? super K,? super V,? extends V> function) is a method that replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Here is a simple usage of the replaceAll() method:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapReplaceAllExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "v1");
        map.put("key2", "v2");

        map.replaceAll((k, v) -> v.toUpperCase());

        // Output: {key1=V1, key2=V2}
        System.out.println(map);
    }
}

Output:

{key1=V1, key2=V2}

In this example, the replaceAll() method is used to replace every value in the map with its uppercase version. The provided function should be non-interfering and stateless.

The benefits of using replace() and replaceAll() methods are:

  • They are more concise and expressive.
  • They can improve code readability and maintainability.
  • They are beneficial while working in a multi-thread environment because they provide additional safety without additional synchronization.
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.