Home Java HashSet Methods remove() Java HashSet remove() Method Definition In Java, remove(o) deletes the element equal to o from a HashSet. It returns true if the element was present and has now been removed, and false if the set did not contain it.
The set shrinks by one when something is removed. Asking to remove an element that is not there is not an error; the call just returns false and the set is unchanged.
An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety .
Syntax One argument: the element to delete.
Set<String> tags = new HashSet<>();
tags.add("java");
boolean a = tags.remove("java"); // true
boolean b = tags.remove("java"); // false (already gone) Call What it does set.remove("java")Deletes the element; true if it was present. set.removeIf(test)Deletes every element that passes the test. it.remove()Deletes the element an Iterator just returned. set.remove(null)Deletes the null element, if one was added.
Set has only remove(Object), so for a Set<Integer> the call set.remove(5) removes the element 5. There is no index version as on a List.
Library declarations // java.util.HashSet<E>
public boolean remove(Object o)
// Declared in Set<E> and Collection<E> Parameters Parameter Description o (Object)The element to remove. It may be null.
Return Value Return Value Description trueAn equal element was in the set and has been removed. falseNo equal element was found, or o has a different type; the set is unchanged.
Important
Calling set.remove inside a for-each loop over the same set usually throws ConcurrentModificationException on the next step. Use iterator.remove(), loop over a copy, or call removeIf (Java 8). An unmodifiable set throws UnsupportedOperationException, and a value of the wrong type is silently not found.
Compare with Similar Methods Ways to delete elements:
Java Examples 1. Unsubscribe 2. The Object parameter 3. Loop over a copy Example 1 — Unsubscribe an E-mail Address Remove a subscriber, remove the same one again, and remove someone who never subscribed.
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashSetRemoveDemo {
public static void main(String[] args) {
Set<String> subscribers = new HashSet<>();
subscribers.add("[email protected] ");
subscribers.add("[email protected] ");
subscribers.add("[email protected] ");
System.out.println("remove bo: " + subscribers.remove("[email protected] "));
System.out.println("remove bo again: " + subscribers.remove("[email protected] "));
System.out.println("remove dee: " + subscribers.remove("[email protected] "));
System.out.println("left: " + new TreeSet<>(subscribers));
}
} How It Works Found and removed. "[email protected] " is in the set, so the first call deletes it and returns true.Already gone. The second request for the same address finds nothing and returns false, without any exception.Never subscribed. "[email protected] " was never added, so that call is false too.Sorted for display. The TreeSet copy prints the two remaining addresses alphabetically.Example 2 — remove() Takes an Object, Not Just E Remove an Integer normally, then try a long and a String that look similar.
import java.util.HashSet;
import java.util.Set;
public class HashSetRemoveTypes {
public static void main(String[] args) {
Set<Integer> codes = new HashSet<>();
codes.add(101);
codes.add(102);
codes.add(103);
System.out.println("remove(103): " + codes.remove(103));
System.out.println("remove(101L): " + codes.remove(101L));
System.out.println("remove(\"102\"): " + codes.remove("102"));
System.out.println("size: " + codes.size());
}
} remove(103): true
remove(101L): false
remove("102"): false
size: 2 How It Works No index confusion. On a set, remove(103) boxes the number and deletes the element 103; it never means "position 103".A Long does not match. 101L becomes a Long, which is never equal to an Integer, so nothing is removed.A String does not match either. The text "102" compiles because the parameter is Object, but it is a different type, so false comes back.Size proves it. Only one removal worked, so two codes remain.Example 3 — Remove Finished Tasks While Looping Over a Copy Loop over a list copy of the set so that remove() on the real set is safe.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashSetRemoveLoop {
public static void main(String[] args) {
Set<String> tasks = new HashSet<>();
tasks.add("todo-1");
tasks.add("todo-2");
tasks.add("done-3");
tasks.add("done-4");
int removed = 0;
for (String id : new ArrayList<>(tasks)) {
if (id.startsWith("done")) {
tasks.remove(id);
removed++;
}
}
System.out.println("removed: " + removed);
System.out.println("tasks left: " + new TreeSet<>(tasks));
}
} removed: 2
tasks left: [todo-1, todo-2] How It Works Loop over a snapshot. new ArrayList<>(tasks) copies the four ids, so the for-each loop walks the copy while the real set changes.No exception. The loop's own iterator belongs to the list, so removing from tasks cannot make it fail with ConcurrentModificationException.Prefix test. startsWith("done") picks "done-3" and "done-4", so removed ends at 2.Remaining work. The two todo ids stay, printed alphabetically through a TreeSet copy.Frequently Asked Questions How do I remove an element from a HashSet in Java? Call set.remove(element). It deletes the element and returns true, or returns false if the element was not in the set.
Does remove() throw an exception if the element is missing? No. It returns false and leaves the set unchanged.
Why do I get ConcurrentModificationException when removing from a HashSet? You called set.remove() while a for-each loop was iterating over the same set. Use Iterator.remove(), removeIf(), or loop over a copy.
How do I remove several elements at once? Use removeAll(collection) to remove the elements of another collection, or removeIf(condition) to remove the ones that pass a test.
Why does remove(5L) not remove the Integer 5? remove() accepts any Object, and a Long is never equal to an Integer. Pass the same type that the set stores.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful
Helpful Share Copy link Suggestion