How to remove elements from a list without writing loops or risking ConcurrentModificationException in Java?

Problem

How to remove elements from a list without writing loops or risking ConcurrentModificationException?

Example Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RemoveIfDemo {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(10, 25, 30, 45, 50));

        // Remove all numbers less than 30
        numbers.removeIf(n -> n < 30);

        System.out.println("After removeIf: " + numbers);
    }
}

Output

After removeIf: [30, 45, 50]

After using removeIf, the list contains only numbers greater than or equal to 30

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *