Java HashSet removeIf() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

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.

Java
Set<Integer> scores = new HashSet<>(Arrays.asList(35, 80, 49));
boolean any = scores.removeIf(s -> s < 50);   // true
System.out.println(scores);                   // [80]
CallWhat 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
Java
// Declared in java.util.Collection<E> (Java 8+), inherited by HashSet
public default boolean removeIf(Predicate<? super E> filter)

Parameters

ParameterDescription
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 ValueDescription
trueAt least one element matched and was removed.
falseNo element matched; the set is unchanged.

Compare with Similar Methods

Choosing how to remove:

MethodHow it differs
remove(o)Removes one known element.
removeAll(c)Removes by membership in another collection.
retainAll(c)Keeps the elements that are in a collection and removes the rest.
iterator() with it.remove()The pre-Java 8 way, with more code.

Java Examples

Example 1 — Drop Failing Scores

Remove every score below 50 and print what is left.

Java
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));
    }
}

How It Works

  1. A lambda as the test. s -> s < 50 is called once for each of the five scores.
  2. 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.
  3. Sorted for display. Copying into a TreeSet shows 50, 80, and 95 in order, whatever order the set stores them in.
  4. 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.

Java
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));
    }
}

How It Works

  1. Five different elements. The empty string, three spaces, and null are all distinct from each other, so the set starts with five.
  2. Method reference. Objects::isNull is a ready-made Predicate; it removes the single null element.
  3. Order of the steps matters. The second test calls s.trim(), which would throw NullPointerException on null, so the nulls had to go first.
  4. 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.

Java
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));
    }
}

How It Works

  1. A bound method reference. stopWords::contains turns the other set's contains() into a Predicate, so each word is tested against it.
  2. Three words go. "the", "on", and "a" are stop words, which leaves cat, sat, and mat.
  3. A captured variable. The lambda reads banned; this works because the variable is never reassigned.
  4. Chained filters. Calling removeIf twice applies the rules one after another, ending with cat and mat.

Frequently Asked Questions

It removes every element for which the given Predicate returns true and returns true if anything was removed. It needs Java 8 or later.
Call set.removeIf(element -> condition). For example, scores.removeIf(s -> s < 50) removes every score below 50.
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.
Use set.removeIf(Objects::isNull), or set.remove(null) because a HashSet holds at most one null.
removeAll(c) removes the elements that are contained in another collection. removeIf(test) removes the elements for which a condition is true.

Next: retainAll()

Keep only the elements found in another collection.

retainAll() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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