How do I remove multiple elements from a list in Java?


The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

boolean removeAll(Collection<?> c)

Parameters

  • c − Collection containing elements to be removed from this list.

Returns

True if this list changed as a result of the call

Throws

  • UnsupportedOperationException − If the removeAll operation is not supported by this list.

  • ClassCastException − If the class of an element of this list is incompatible with the specified collection (optional).

  • NullPointerException − If this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.

Example

Following is the example showing the usage of removeAll() method −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
      List<Integer> list1 = new ArrayList<>(Arrays.asList(6,7,8,9));
      System.out.println("List: " + list);
      list.removeAll(list1);
      System.out.println("Updated List: " + list);
   }
}

Output

This will produce the following result −

List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Updated List: [0, 1, 2, 3, 4, 5]

Updated on: 09-May-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements