What is the LinkedHashMap.remove(key) method in Java?
A LinkedHashMap is the same as a HashMap, except that a LinkedHashMap maintains the insertion order, whereas a HashMap doesn’t. Internally, the LinkedHashMap uses a doubly-linked list to maintain the insertion order.
The remove method
In LinkedHashMap, we can use the remove method to remove the mapping of the specified key.
Syntax
public V remove(Object key)
Parameters
The key whose mapping is to be removed is passed as an argument.
Return value
-
If there is a mapping present for the specified key, then the mapping is removed and the removed value is returned.
-
If there is no mapping present for the specified key, then
nullis returned.
Code
The below example shows how to use the remove method.
import java.util.LinkedHashMap;class RemoveExample {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.remove(1);System.out.println("\nThe return value for remove method is -" + returnValue);System.out.println("The map is -" + map );returnValue = map.remove(3);System.out.println("\nThe return value for remove method is -" + returnValue);System.out.println("The map is -" + map );}}
Explanation
In the code above:
-
In line 1, we imported the
LinkedHashMapclass. -
In line 5, we created a
LinkedHashMapobject with the namemap. -
In lines 6 and 7, we used the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 10, we used the
removemethod to remove the mapping for the key1. -
In line 14, we used the
removemethod to remove the mapping for the key3. There is no such entry present, sonullwill be returned.