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