Java – Remove elements in HashMap

Element in HashMap can be removed by remove() method. In remove method, we can pass object to remove.

 hashmap.remove(object);

Example of removing element in HashMap

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapRemoveExample {

    public static void main(String[] args) {

        HashMap<Object,String> hm=new HashMap<Object,String>();

        hm.put(new Integer(2), "Two");
        hm.put(new Integer(1), "One");
        hm.put(new Integer(3), "Three");
        hm.put(new Integer(4), "Four");

        // remove hashmap object 
        hm.remove(new Integer(3));

        Set s=hm.entrySet();

        Iterator it=s.iterator();

        while(it.hasNext())
        {
            Map.Entry m =(Map.Entry)it.next();

            int key=(Integer)m.getKey();

            String value=(String)m.getValue();

            System.out.println("Key :"+key+" value :"+value);
        }
    }
}

Tags:

Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post