What is the LinkedHashMap.replace method in Java?

A LinkedHashMap is the same as a HashMap, except the LinkedHashMap maintains the insertion order, whereas the HashMap doesn’t. Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order. Read more about LinkedHashMap here.

In LinkedHashMap, we can use the replace method to replace the value associated with the key of the LinkedHashMap. If there is no value associated with the key, then no action is performed.

Syntax

public V replace(K key, V value)

Arguments

  • key: The key for which the new value is to be updated.
  • value: The new value to be updated.

Return value

  • If the key already has a value, then the new value is updated and the old value is returned.

  • If there was no mapping for the key, then null is returned.

Code

The example below shows how to use the replace method.

import java.util.LinkedHashMap;
class ReplaceExample {
public static void main( String args[] ) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("The map is -" + map );
String returnValue = map.replace(1, "ONE");
System.out.println("\nThe map is -" + map );
System.out.println("The return value of the replace method is -" + returnValue);
returnValue = map.replace(3, "three");
System.out.println("\nThe map is -" + map );
System.out.println("The return value of the replace method is -" + returnValue);
}
}

Explanation

In the code above:

  • In line 1, we import the LinkedHashMap class.

  • In line 4, we create a LinkedHashMap object with the name map.

  • In lines 5 and 6, we use the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 10, we use the replace method to replace the value of the key 1 with the value "ONE". This method will check if there is any mapping for the key 1. In our case, the key 1 is associated with the value "one". So, the new value "ONE" is updated for the key 1, and the old value is returned.

  • In line 14, we use the replace method to replace the value of the key 3 with the value "THREE". This method will check if there is any mapping for the key 3. In our case, the key 3 has no mapping, so null will be returned.