Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Remove from Map


How to remove an element from the Map?


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.


How to remove an element using the remove() Method?


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

Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Map x = new HashMap<>();

        x.put("John", "Is a Name");
        x.put("Java", "Is a Language");

        x.remove("John");

        System.out.println(x);
    }
}


Output :



  {Java=Is a Language}

So, in the above code we have created a Map,


Map x = 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.

Spring_Boot

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.

Spring_Boot

And we get the below output,

Output :



  {Java=Is a Language}

How to remove all the elements from the Map using clear() Method?


The clear() Method can be used to remove all the elements from the Map.


Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Map x = new HashMap<>();

        x.put("John", "Is a Name");
        x.put("Java", "Is a Language");

        x.clear();

        System.out.println(x);
    }
}


Output :



  {}

So, in the above code we have created a Map,


Map x = 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.

Spring_Boot

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.

Output :



  {}