The ArrayList.removeIf() iterates the list and removes all of the elements of this ArrayList that satisfy the given Predicate.
1. ArrayList.removeIf() API
The removeIf()
takes a single argument of type Predicate. The Predicate interface is a functional interface that represents a condition (boolean-valued function) of one argument. It checks that is a given argument met the condition or not.
public boolean removeIf(Predicate<? super E> filter);
Method parameter – filter predicate that returns true
for elements to be removed.
Method returns – true
if any elements were removed from this list.
Method throws – NullPointerException
if predicate is null
.
2. ArrayList.removeIf() Example
The following Java programs use removeIf() method to remove elements that match a Predicate.
2.1. Remove All Even Numbers
In this simple example, we have a list of odd/even numbers and remove all even numbers from the list.
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
numbers.removeIf(number -> number % 2 == 0);
System.out.println(numbers);
Program output.
[1, 3, 5, 7, 9]
2.2. Remove Objects by Field
In this simple example, we have a list of employees, and we are removing all employees whose names start with char 'P'
. The predicate, employee.getName().startsWith(“P”) matches the name of each Employee and returns true if the name starts with P.
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21)));
employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22)));
employees.add(new Employee(3l, "Piyush", LocalDate.of(2018, Month.APRIL, 25)));
employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23)));
employees.add(new Employee(2l, "Pawan", LocalDate.of(2018, Month.APRIL, 24)));
Predicate<Employee> condition = employee -> employee.getName().startsWith("P");
employees.removeIf(condition);
System.out.println(employees);
Program output.
[
Employee [id=1, name=Alex, dob=2018-04-21],
Employee [id=4, name=Brian, dob=2018-04-22],
Employee [id=5, name=Charles, dob=2018-04-23]
]
That’s all for the ArrayList removeIf() in Java.
Happy Learning !!
Read More: ArrayList Java Docs and Predicate Java Docs