How to remove all elements from a Collection in another Collection

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our Collection i.e. ArrayList −

List<Integer>list = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(200);
list.add(200);
list.add(300);
list.add(400);
list.add(400);
list.add(500);

Now, create another Collection −

List <Integer>list2 = new ArrayList<Integer>();
list2.add(100);
list2.add(200);
list2.add(300);
list2.add(400);

To remove all elements from a Collection in another Collection, try the following with list and list2 as our two Collections −

list.removeAll(list2);

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List<Integer>list = new ArrayList<Integer>();
      list.add(100);
      list.add(200);
      list.add(200);
      list.add(200);
      list.add(300);
      list.add(400);
      list.add(400);
      list.add(500);
      List <Integer>list2 = new ArrayList<Integer>();
      list2.add(100);
      list2.add(200);
      list2.add(300);
      list2.add(400);
      list.removeAll(list2);
      System.out.println("Resultant list = "+list);
   }
}

Output

Resultant list = [500]
raja
Published on 24-Apr-2019 14:00:30
Advertisements