Last Updated : 11 Jul, 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<String> 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);
}
}
Set1 before removeAll(): [Geek4, Geek3, Geek2, Geek1] Set1 after removeAll(): [Geek2, Geek1]Syntax of removeAll() Method
boolean removeAll(Collection<?> c)
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);
}
}
Set1 after removing Set2 elements from it: [Geek1] Was the collection modified? true
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4