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 to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources