Java Collection removeAll() Method with Examples
Last Updated :
24 Oct, 2023
The removeAll() method of Java Collection removes those elements from the collection that are contained in the collection which is given as an argument to function.
Syntax
boolean removeAll(Collection<?> c);
Parameters:
- c is the collection containing elements that are removed from the calling collection.
Return Type:
It returns a boolean value. It returns true if the calling collection was modified by the removeAll() method else it returns false.
Example of Collection removeAll() method
Below is the implementation of the above method:
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
class Main {
public static void main(String[] args)
{
Collection<Integer> list1 = new ArrayList<>();
list1.add( 1 );
list1.add( 2 );
list1.add( 3 );
list1.add( 4 );
System.out.println( "Original List: " + list1);
Collection<Integer> list2 = new ArrayList<>();
list2.add( 2 );
list2.add( 4 );
System.out.println(
"List containing elements to be removed from the calling collection(list1): "
+ list2);
boolean isRemoved = list1.removeAll(list2);
System.out.println( "Elements removed from List1: "
+ isRemoved);
System.out.println( "Modified list1 after deletion: "
+ list1);
}
}
|
Output
Original List: [1, 2, 3, 4]
List containing elements to be removed from the calling collection(list1): [2, 4]
Elements removed from List1: true
Modified list1 after deletion: [1, 3]
Example 2:
Another example where the collection passed as an argument doesn’t contain any element which could be deleted in original collection.
Java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class GFG {
public static void main(String[] args)
{
List<Integer> list1 = new ArrayList<Integer>();
list1.add( 1 );
list1.add( 2 );
list1.add( 3 );
list1.add( 4 );
System.out.println( "Original List: " + list1);
List<Integer> list2 = new ArrayList<Integer>();
list2.add( 7 );
list2.add( 8 );
System.out.println(
"List containing elements to be removed from the calling collection(list1): "
+ list2);
boolean isRemoved = list1.removeAll(list2);
System.out.println( "Elements removed from List1: "
+ isRemoved);
System.out.println( "Modified list1 after deletion: "
+ list1);
}
}
|
Output
Original List: [1, 2, 3, 4]
List containing elements to be removed from the calling collection(list1): [7, 8]
Elements removed from List1: false
Modified list1 after deletion: [1, 2, 3, 4]
Share your thoughts in the comments
Please Login to comment...