Open In App

How to Remove Elements from a LinkedHashMap in Java?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Remove 
// Elements from a LinkedHashMap
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // create a LinkedHashMap
        LinkedHashMap<String, Integer> map
            = new LinkedHashMap<String, Integer>();
  
        // add elements(key-value pairs) to our map
        map.put("Java", 4999);
        map.put("Python", 2999);
        map.put("Go", 3999);
        map.put("Rust", 1999);
  
        System.out.println("Before, LinkedHashMap is: "
                           + map);
  
        // remove the entry whose key is 'Python'
        Integer ret = map.remove("Python");
  
        // print the returned value after removing entry for
        // '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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads