Skip to Content

Remove an element from Collection using Java Iterator Example

  1. /*
  2.   Remove an element from Collection using Java Iterator Example
  3.   This Java Example shows how to remove an element from underlying Collection using
  4.   Java Iterator's remove method.
  5. */
  6.  
  7. import java.util.Iterator;
  8. import java.util.ArrayList;
  9.  
  10. public class RemoveElementThroughIteratorExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an ArrayList object
  15.     ArrayList aList = new ArrayList();
  16.    
  17.     //populate ArrayList object
  18.     aList.add("1");
  19.     aList.add("2");
  20.     aList.add("3");
  21.     aList.add("4");
  22.     aList.add("5");
  23.    
  24.    
  25.     System.out.println("ArrayList before removal : ");
  26.     for(int i=0; i< aList.size(); i++)
  27.       System.out.println(aList.get(i));
  28.      
  29.     //get an Iterator
  30.     Iterator itr = aList.iterator();
  31.    
  32.     //remove 2 from ArrayList using Iterator's remove method.
  33.     String strElement = "";
  34.     while(itr.hasNext()){
  35.      
  36.       /*
  37.         Iterator's next method returns an Object so we need to cast it into
  38.         appropriate class before using it.
  39.       */
  40.       strElement = (String)itr.next();
  41.       if(strElement.equals("2"))
  42.       {
  43.         /*
  44.           Remove an element using remove() method of Iterator
  45.           Remove method removes an element from underlying collection and
  46.           it may throw a UnsupportedOperationException if the remove
  47.           operation is not supported.
  48.         */
  49.         itr.remove();
  50.         break;
  51.       }
  52.      
  53.      
  54.      
  55.     }
  56.    
  57.     System.out.println("ArrayList after removal : ");
  58.     for(int i=0; i< aList.size(); i++)
  59.       System.out.println(aList.get(i));
  60.  
  61.   }
  62. }
  63.  
  64. /*
  65. Output would be
  66. ArrayList before removal :
  67. 1
  68. 2
  69. 3
  70. 4
  71. 5
  72. ArrayList after removal :
  73. 1
  74. 3
  75. 4
  76. 5
  77. */