Java Collection How to - Remove Another Collection








Question

We would like to know how to remove Another Collection.

Answer

If an element from the passed-in collection is in the list multiple times, all instances are removed.

import java.util.ArrayList;
import java.util.List;
//  ww w. j a v a  2s . c  om
public class MainClass {
  public static void main(String args[]) throws Exception {

    List list = new ArrayList();
    list.add("A");
    list.add("A");
    list.add("B");
    list.add("B");
    list.add("C");
    list.add("C");

    List list2 = new ArrayList();
    list2.add("A");
    list2.add("B");
    list2.add("C");
    list.removeAll(list2);

    System.out.println(list);
  }
}
 

The code above generates the following result.