Remove LinkedHashMap elements

We can remove elements from LinkedHashMap using methods provided in it

There are 2 methods listed below which can be used to remove elements from LinkedHashMap

Object remove(Object key)

Removes the mapping for the specified key from this map if present.

Void clear()

Removes all of the mappings from this map

Example

  1. import java.util.*;
  2. public class LinkedHashMapRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
  6. lhm.put(1, “One”);
  7. lhm.put(2, “Two”);
  8. lhm.put(3, “Three”);
  9. System.out.println(“Initial HashMap);
  10. System.out.println(lhm);
  11.  
  12. lhm.remove(1);
  13. System.out.println(LinkedHashMap after removing 1 element”);
  14. System.out.println(lhm);
  15.  
  16. lhm.clear();
  17. System.out.println(LinkedHashMap after removing all elements”);
  18. System.out.println(lhm);
  19.  
  20. }
  21. }
import java.util.*;
public class LinkedHashMapRemoveExample {
public static void main(String args[]) {

LinkedHashMap<Integer,String> lhm = new LinkedHashMap<>();
lhm.put(1, “One”);
lhm.put(2, “Two”);
lhm.put(3, “Three”);
System.out.println(“Initial HashMap”);
System.out.println(lhm);

lhm.remove(1);
System.out.println(LinkedHashMap after removing 1 element”);
System.out.println(lhm);

lhm.clear();
System.out.println(LinkedHashMap after removing all elements”);
System.out.println(lhm);

}
}


We can see that, clear() method has removed all elements in the Map and remove() method has removed only specified element from the map.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on