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
- 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);
- }
- }
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.