How to Remove Elements from a LinkedHashMap in Java?
Last Updated :
25 Jan, 2024
A LinkedHashMap is a part of the Collection Framework from java.util package Java and is similar to a HashMap, except that a LinkedHashMap preserves the insertion order among the keys/entries.
In this article, we will look at how to remove the elements from a LinkedHashMap in Java.
Program to Remove Elements from a LinkedHashMap in Java
The remove() method is the default method, which is usually used to remove an element from any data structure from the Collection Framework. We can use the remove() method to remove a single specified key from the LinkedHashMap.
Syntax:
<map-object>.remove(Object key)
Below is the implementation to Remove Elements from a LinkedHashMap in Java:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashMap<String, Integer> map
= new LinkedHashMap<String, Integer>();
map.put( "Java" , 4999 );
map.put( "Python" , 2999 );
map.put( "Go" , 3999 );
map.put( "Rust" , 1999 );
System.out.println( "Before, LinkedHashMap is: "
+ map);
Integer ret = map.remove( "Python" );
System.out.println(
"The value returned by the removal 'Python' key is : "
+ ret);
System.out.println( "After, LinkedHashMap is: "
+ map);
}
}
|
Output
Before, LinkedHashMap is: {Java=4999, Python=2999, Go=3999, Rust=1999}
The value returned by the removal 'Python' key is : 2999
After, LinkedHashMap is: {Java=4999, Go=3999, Rust=1999}
Note :
- To remove all the elements from the LinkedHashMap, you can directly use the clear() method.
- You should not use LinkedInHashMap.remove() when iterating over elements using Iterator as it will throw ConcurrentModificationException.
To know another method to remove elements from LinkedHashMap in Java refer to Remove() using Iterator Object.
Share your thoughts in the comments
Please Login to comment...