Home Java HashSet Methods removeIf() Java HashSet removeIf() Method Definition In Java 8 and later, removeIf(filter) removes from a HashSet every element for which the Predicate filter returns true. It returns true if at least one element was removed.
It replaces a hand-written Iterator loop with iterator.remove(). You describe which elements to throw away with a lambda such as n -> n < 50 or a method reference, and the set does the looping safely.
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 . removeIf() was added in Java 8 as a default method of Collection, and HashSet inherits it.
Syntax One argument: a Predicate that says which elements to remove.
Set<Integer> scores = new HashSet<>(Arrays.asList(35, 80, 49));
boolean any = scores.removeIf(s -> s < 50); // true
System.out.println(scores); // [80] Call What it does set.removeIf(n -> n % 2 == 0)Removes the even numbers. set.removeIf(String::isEmpty)Removes empty strings with a method reference. set.removeIf(Objects::isNull)Removes the null element, if present. set.removeIf(other::contains)Removes everything that another collection contains.
The lambda may read local variables as long as they are not changed afterwards (effectively final). It must not add to or remove from the same set.
Library declarations // Declared in java.util.Collection<E> (Java 8+), inherited by HashSet
public default boolean removeIf(Predicate<? super E> filter) Parameters Parameter Description filter (Predicate<? super E>)A test applied to each element. Elements for which it returns true are removed. It must not be null.
Return Value Return Value Description trueAt least one element matched and was removed. falseNo element matched; the set is unchanged.
Important
A null filter throws NullPointerException. If the Predicate changes the set itself, you can get ConcurrentModificationException. The default implementation removes elements one by one, so an exception thrown from the test leaves the elements removed so far deleted. A test such as s.isEmpty() throws NullPointerException for the null element, so remove nulls first. Unmodifiable sets throw UnsupportedOperationException.
Compare with Similar Methods Choosing how to remove:
Java Examples 1. Remove by a number test 2. Clean null and blank values 3. Use another set Example 1 — Drop Failing Scores Remove every score below 50 and print what is left.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashSetRemoveIfDemo {
public static void main(String[] args) {
Set<Integer> scores = new HashSet<>(Arrays.asList(35, 80, 49, 95, 50));
boolean removed = scores.removeIf(s -> s < 50);
System.out.println("removed any: " + removed);
System.out.println("passed: " + new TreeSet<>(scores));
System.out.println("removed again: " + scores.removeIf(s -> s < 50));
}
} removed any: true
passed: [50, 80, 95]
removed again: false How It Works A lambda as the test. s -> s < 50 is called once for each of the five scores.Two matches. 35 and 49 fail the test and are deleted, so the result is true. The score 50 stays because 50 is not less than 50.Sorted for display. Copying into a TreeSet shows 50, 80, and 95 in order, whatever order the set stores them in.Idempotent. Running the same filter again finds nothing below 50, so it returns false.Example 2 — Clean Up null and Blank Entries Remove the null element with a method reference first, then the blank strings with a lambda.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
public class HashSetRemoveIfClean {
public static void main(String[] args) {
Set<String> raw = new HashSet<>();
raw.add("java");
raw.add("");
raw.add(" ");
raw.add(null);
raw.add("sql");
System.out.println("start: " + raw.size());
raw.removeIf(Objects::isNull);
System.out.println("after null removal: " + raw.size());
raw.removeIf(s -> s.trim().isEmpty());
System.out.println("after blank removal: " + raw.size());
System.out.println("clean: " + new TreeSet<>(raw));
}
} start: 5
after null removal: 4
after blank removal: 2
clean: [java, sql] How It Works Five different elements. The empty string, three spaces, and null are all distinct from each other, so the set starts with five.Method reference. Objects::isNull is a ready-made Predicate; it removes the single null element.Order of the steps matters. The second test calls s.trim(), which would throw NullPointerException on null, so the nulls had to go first.Blanks removed. Both "" and " " have an empty trimmed form, leaving "java" and "sql".Example 3 — Remove Stop Words with a Method Reference Use stopWords::contains as the test, then add a rule that uses a local variable.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashSetRemoveIfRefs {
public static void main(String[] args) {
Set<String> words = new HashSet<>(Arrays.asList("the", "cat", "sat", "on", "a", "mat"));
Set<String> stopWords = new HashSet<>(Arrays.asList("the", "on", "a"));
words.removeIf(stopWords::contains);
System.out.println("without stop words: " + new TreeSet<>(words));
String banned = "sat";
words.removeIf(w -> w.equals(banned));
System.out.println("without sat: " + new TreeSet<>(words));
}
} without stop words: [cat, mat, sat]
without sat: [cat, mat] How It Works A bound method reference. stopWords::contains turns the other set's contains() into a Predicate, so each word is tested against it.Three words go. "the", "on", and "a" are stop words, which leaves cat, sat, and mat.A captured variable. The lambda reads banned; this works because the variable is never reassigned.Chained filters. Calling removeIf twice applies the rules one after another, ending with cat and mat.Frequently Asked Questions What does HashSet removeIf() do? It removes every element for which the given Predicate returns true and returns true if anything was removed. It needs Java 8 or later.
How do I remove elements from a HashSet by condition? Call set.removeIf(element -> condition). For example, scores.removeIf(s -> s < 50) removes every score below 50.
Is removeIf() safe to use instead of a for-each loop with remove()? Yes. It removes through the set's own iterator, so it does not throw ConcurrentModificationException the way set.remove() inside a for-each loop does.
How do I remove null from a HashSet with removeIf()? Use set.removeIf(Objects::isNull), or set.remove(null) because a HashSet holds at most one null.
What is the difference between removeIf() and removeAll()? removeAll(c) removes the elements that are contained in another collection. removeIf(test) removes the elements for which a condition is true.
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.
10 people found this page helpful
Helpful Share Copy link Suggestion