Java Iterator remove element from Collection

Description

Java Iterator remove element from Collection


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    String[] colors = { "CSS", "Java", "HTML", "Javascript", "SQL" };
    List<String> list = new ArrayList<String>();

    for (String color : colors)
      list.add(color);//from   w w w  .  j a va 2  s .  co m

    // add elements in removeColors array to removeList
    String[] removeColors = { "Java", "CSS", "SQL" };
    List<String> removeList = new ArrayList<String>();

    for (String color : removeColors)
      removeList.add(color);

    System.out.println(list);

    // remove from list the colors contained in removeList
    removeColors(list, removeList);

    System.out.println(list);
  }

  // remove colors specified in collection2 from collection1
  private static void removeColors(Collection<String> collection1, Collection<String> collection2) {
    // get iterator
    Iterator<String> iterator = collection1.iterator();

    // loop while collection has items
    while (iterator.hasNext()) {
      if (collection2.contains(iterator.next()))
        iterator.remove(); // remove current element
    }
  }
}



PreviousNext

Related