Java Collection remove element from another Collection

Description

Java Collection remove element from another 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 = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
    List<String> list = new ArrayList<String>();

    for (String color : colors)
      list.add(color); //  w w  w.  j a va 2 s .c om

    // add elements in removeColors array to removeList
    String[] removeColors = { "RED", "WHITE", "BLUE" };
    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
  public 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