Let us say, we have a Map that contains,
John, Is a Name Java, Is a Language
As Key and Value pair.
Now, if you want to remove the entries from a Map, remove() and clear() Method can be used.
Let us look at the remove() Method first.
The remove() Method can be used to remove an item from the Map.
Let us say, we want to remove the entry where the Key is 5 and Value is Is a Number.
John, Is a Name
import java.util.*; public class MyApplication { public static void main(String[] args) { Mapx = new HashMap<>(); x.put("John", "Is a Name"); x.put("Java", "Is a Language"); x.remove("John"); System.out.println(x); } }
So, in the above code we have created a Map,
Mapx = new HashMap<>();
And inserted the entries as Key and Value pairs using put() method.
x.put("John", "Is a Name"); x.put("Java", "Is a Language");
Below is how they are placed in the Map.
Now, we are supposed to delete the value of the Key, John.
John, Is a Name
So, we have used the remove() method to remove it.
x.remove("John");
And the entry for the Key John is deleted for the Map.
And we get the below output,
The clear() Method can be used to remove all the elements from the Map.
import java.util.*; public class MyApplication { public static void main(String[] args) { Mapx = new HashMap<>(); x.put("John", "Is a Name"); x.put("Java", "Is a Language"); x.clear(); System.out.println(x); } }
So, in the above code we have created a Map,
Mapx = new HashMap<>();
And inserted the entries as Key and Value pairs using put() method.
x.put("John", "Is a Name"); x.put("Java", "Is a Language");
Below is how they are placed in the Map.
And we have used the clear() method to remove all the elements from the Map.
x.clear()
And the print statement, prints an empty Map.