Set removeAll() Method in Java (original) (raw)
Last Updated : 06 Feb, 2025
In Java, the **removeAll() method is part of the Collection interface. It is used to remove all elements from a collection that are present in another collection.
**Example 1: This example demonstrates **how the removeAll() method removes all elements from the first **set **that are also present in the second set.
Java `
// Java Program to demosntrates // the working of Set removeAll() import java.util.HashSet; import java.util.Set;
public class Geeks { public static void main(String[] args) { // Adding elements in the first set Set s1 = new HashSet<>(); s1.add("Geek1"); s1.add("Geek2"); s1.add("Geek3"); s1.add("Geek4");
// Adding elements in the second set
Set<String> s2 = new HashSet<>();
s2.add("Geek3");
s2.add("Geek4");
System.out.println("Set1 before removeAll(): "
+ s1);
// Remove all elements of s2 from s1
s1.removeAll(s2);
System.out.println("Set1 after removeAll(): "
+ s1);
}
}
`
Output
Set1 before removeAll(): [Geek4, Geek3, Geek2, Geek1] Set1 after removeAll(): [Geek2, Geek1]
Syntax of removeAll() Method
boolean removeAll(Collection<?> c)
- **Parameter: The collection "c" contains the elements to be removed from the calling collection. If an element in c matches any element in the original collection, it will be removed.
- **Return Type: This method return "true" if elements are removed, otherwise it return "false".
**Example 2: This example shows how removeAll() returns a boolean indicating whether any elements were removed from the first set by comparing it to the second set.
Java `
// Java program to demosntrates that // removeAll() returns boolean value import java.util.HashSet; import java.util.Set;
public class Geeks { public static void main(String[] args) {
Set<String> s1 = new HashSet<>();
s1.add("Geek1");
s1.add("Geek2");
s1.add("Geek3");
Set<String> s2 = new HashSet<>();
s2.add("Geek2");
s2.add("Geek3");
// Removing elements that
// exist in s2 from s1
boolean res1 = s1.removeAll(s2);
System.out.println("Set1 after removing Set2 elements from it: "
+ s1);
System.out.println("Was the collection modified? "
+ res1);
}
}
`
Output
Set1 after removing Set2 elements from it: [Geek1] Was the collection modified? true