Saturday 26 July 2014

Remove entries from HashMap while iterating

It is possible to remove elements from HashHap using keySet() and entrySet(), while iterating.

Using keySet
import java.util.*;
public class RemoveFromHashMap {
    public static void main(String args[]){
        HashMap<Integer, String> myMap = new HashMap<> ();
        
        /* Add Elements to myMap */
        for(int i=0; i<10;i++)
            myMap.put(i, "value " + i);
        
        System.out.println("Size of myMap is "+ myMap.size());
        
        Set<Integer> mySet = myMap.keySet();
        Iterator<Integer> iter = mySet.iterator();
        
        while(iter.hasNext()){
            int i = iter.next();
            if(i%2 == 0)
                iter.remove();
        }
        
        System.out.println("Size of myMap is "+ myMap.size());
        
    }
}

Output
Size of myMap is 10
Size of myMap is 5

Using entrySet
import java.util.*;
public class RemoveFromHashMap {
    public static void main(String args[]){
        HashMap<Integer, String> myMap = new HashMap<> ();
        
        /* Add Elements to myMap */
        for(int i=0; i<10;i++)
            myMap.put(i, "value " + i);
        
        System.out.println("Size of myMap is "+ myMap.size());
        
        Set<Map.Entry<Integer,String>> entrySet = myMap.entrySet();
        
        Iterator<Map.Entry<Integer, String>> iter = entrySet.iterator();
        while(iter.hasNext()){
            int i = iter.next().getKey();
            if(i%2 == 0)
                iter.remove();
        }
        
        System.out.println("Size of myMap is "+ myMap.size());
        
    }
}

Output
Size of myMap is 10
Size of myMap is 5







                                                             Home

No comments:

Post a Comment