Of course! The removeIf() method in Java is a powerful and convenient way to remove elements from a collection (like a List) based on a condition.

Here's a complete breakdown of how to use it, from the basic syntax to advanced examples.
What is removeIf()?
removeIf() is a default method in the java.util.Collection interface. This means it's available not just for List, but also for Set, Queue, and other collection types.
It removes all elements from the collection that satisfy a given predicate (a condition). It was introduced in Java 8 as part of the Stream API, making it much more readable and concise than older, manual ways of removing elements.
Basic Syntax
The method signature is:

default boolean removeIf(Predicate<? super E> filter)
default: This means it's a default implementation in theCollectioninterface. Classes likeArrayListdon't have to write their own version; they just inherit it.boolean: The return type. It returnstrueif any elements were removed, andfalseif no elements were removed.removeIf: The name of the method.Predicate<? super E> filter: This is the key part.Predicate: A functional interface (a single-method interface) that represents a boolean-valued function of one argument. It has one method:test(T t), which returnstrueorfalse.? super E: This means the predicate can accept an object of typeE(the collection's element type) or any of its superclasses. This gives some flexibility.filter: This is the lambda expression or method reference you provide that defines the condition for removal. If thefilter'stest()method returnstruefor an element, that element is removed.
How to Use removeIf() with Examples
Let's start with a simple List of strings.
import java.util.ArrayList;
import java.util.List;
public class RemoveIfExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
names.add("Anna");
names.add("Eve");
System.out.println("Original List: " + names);
// Original List: [Alice, Bob, Charlie, David, Anna, Eve]
}
}
Example 1: Removing elements with a simple condition (Lambda Expression)
Let's remove all names that start with the letter 'A'.
// Remove all names that start with 'A'
names.removeIf(name -> name.startsWith("A"));
System.out.println("List after removing names starting with 'A': " + names);
// List after removing names starting with 'A': [Bob, Charlie, David, Eve]
How it works:
name -> name.startsWith("A")is a lambda expression that implements thePredicate<String>interface.- For each
namein the list, theremoveIfmethod calls this lambda. - If
name.startsWith("A")returnstrue(e.g., for "Alice" and "Anna"), that element is removed from the list.
Example 2: Removing elements based on object state
Let's create a list of Person objects and remove people who are older than 30.

import java.util.ArrayList;
import java.util.List;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class RemoveIfObjectExample {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 32));
people.add(new Person("Charlie", 28));
people.add(new Person("David", 45));
System.out.println("Original List: " + people);
// Original List: [Alice (25), Bob (32), Charlie (28), David (45)]
// Remove people older than 30
people.removeIf(person -> person.getAge() > 30);
System.out.println("List after removing people older than 30: " + people);
// List after removing people older than 30: [Alice (25), Charlie (28)]
}
}
Example 3: Using a Method Reference
If your condition is simply checking if an object is null, you can use a method reference for an even cleaner syntax.
List<String> items = new ArrayList<>();
items.add("Apple");
items.add(null);
items.add("Banana");
items.add(null);
items.add("Cherry");
System.out.println("Original List: " + items);
// Original List: [Apple, null, Banana, null, Cherry]
// Remove all null elements
items.removeIf(java.util.Objects::isNull);
System.out.println("List after removing nulls: " + items);
// List after removing nulls: [Apple, Banana, Cherry]
java.util.Objects::isNull is a method reference that is equivalent to the lambda x -> x == null.
Performance and How it Works
It's useful to know how removeIf() is implemented under the hood, especially if you're concerned about performance.
The implementation typically iterates through the collection and removes elements that match the predicate. The exact algorithm can vary slightly between collection types, but a common approach is:
- Create an iterator for the collection.
- Loop through the collection using the iterator's
hasNext()andnext()methods. - For each element, call the
filter.test()method. - If
test()returnstrue, call the iterator'sremove()method.
This is highly efficient because it avoids the problems of modifying a list while looping over it with a traditional for loop.
The Old Way (Before Java 8) - Dangerous!
Imagine trying to do the same thing with a classic for loop:
// DANGEROUS - DO NOT DO THIS!
for (int i = 0; i < names.size(); i++) {
if (names.get(i).startsWith("A")) {
names.remove(i); // This causes problems!
}
}
This code will throw an IndexOutOfBoundsException or skip elements. When you remove an element at index i, all subsequent elements shift one position to the left. The loop counter i then increments, and you effectively skip the element that has moved into the current i position.
removeIf() handles all this complexity safely and efficiently.
Complete Runnable Example
Here is a full, runnable example that combines several removeIf scenarios.
import java.util.ArrayList;
import java.util.List;
public class CompleteRemoveIfDemo {
public static void main(String[] args) {
// 1. Example with a List of Strings
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Strawberry");
fruits.add("Blueberry");
fruits.add("Grape");
System.out.println("--- String List Example ---");
System.out.println("Original: " + fruits);
// Remove fruits that do not contain the letter 'e'
fruits.removeIf(fruit -> !fruit.contains("e"));
System.out.println("After removing fruits without 'e': " + fruits);
// 2. Example with a List of custom objects
List<Product> products = new ArrayList<>();
products.add(new Product("Laptop", 1200.00, 5));
products.add(new Product("Mouse", 25.00, 15));
products.add(new Product("Keyboard", 75.00, 8));
products.add(new Product("Monitor", 300.00, 3));
System.out.println("\n--- Product List Example ---");
System.out.println("Original: " + products);
// Remove products with stock less than 5
products.removeIf(p -> p.getStock() < 5);
System.out.println("After removing low-stock items: " + products);
// 3. Example with a List containing nulls
List<String> data = new ArrayList<>();
data.add("Value 1");
data.add(null);
data.add("Value 2");
data.add(null);
System.out.println("\n--- Null Removal Example ---");
System.out.println("Original: " + data);
// Remove all null elements using a method reference
data.removeIf(java.util.Objects::isNull);
System.out.println("After removing nulls: " + data);
}
}
// A simple Product class for the example
class Product {
private String name;
private double price;
private int stock;
public Product(String name, double price, int stock) {
this.name = name;
this.price = price; 