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: Thekeyfor which the new value is to be updated.value: The newvalueto be updated.
Return value
-
If the
keyalready has a value, then the new value is updated and the old value is returned. -
If there was no mapping for the key, then
nullis 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
LinkedHashMapclass. -
In line 4, we create a
LinkedHashMapobject with the namemap. -
In lines 5 and 6, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 10, we use the
replacemethod to replace the value of the key1with the value"ONE". This method will check if there is any mapping for the key1. In our case, the key1is associated with the value"one". So, the new value"ONE"is updated for the key1, and the old value is returned. -
In line 14, we use the
replacemethod to replace the value of the key3with the value"THREE". This method will check if there is any mapping for the key3. In our case, the key3has no mapping, sonullwill be returned.