Java Iterator.remove()

Syntax

Iterator.remove() has the following syntax.

void remove()

Example

In the following code shows how to use Iterator.remove() method.


import java.util.ArrayList;
import java.util.Iterator;
/*ww  w.  j  a  v  a  2s  .  c om*/
public class Main {
  public static void main(String[] args) {
    ArrayList aList = new ArrayList();
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("java2 s .com");
    System.out.println("ArrayList: ");
    System.out.println(aList);
    Iterator itr = aList.iterator();
    String strElement = "";
    while (itr.hasNext()) {
      strElement = (String) itr.next();
      if (strElement.equals("2")) {
        itr.remove();
        break;
      }
    }
    System.out.println("ArrayList after removal : ");
    System.out.println(aList);
  }
}

The output: