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 null is 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 LinkedHashMap class.

  • In line 5, we created a LinkedHashMap object with the name map.

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

  • In line 10, we used the remove method to remove the mapping for the key 1.

  • In line 14, we used the remove method to remove the mapping for the key 3. There is no such entry present, so null will be returned.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources