ArrayList removeIf() – remove objects by field

ArrayList removeIf() iterate the list and removes all of the elements of this list that satisfy the given predicate.

1. ArrayList removeIf() method

The removeIf() method takes 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 a predicate which returns true for elements to be removed.
Method returnstrue if any elements were removed.
Method throwsNullPointerException if predicate is null.

2. ArrayList removeIf() example

Java program to use removeIf() method to remove elements which match a given condition in form of a predicate.

2.1. Remove even numbers from a list of numbers

In this simple example, we have a list of odd/even numbers and we are removing all even numbers from the list.

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

public class ArrayListExample 
    public static void main(String[] args) throws CloneNotSupportedException 
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));

        numbers.removeIf( number -> number%2 == 0 );

Program output.

[1, 3, 5, 7, 9]

2.2. Remove remove objects by field value

In this simple example, we have a list of employees and we are removing all employees whose name start with char 'P'.

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.function.Predicate;

public class ArrayListExample 
    public static void main(String[] args) throws CloneNotSupportedException 
        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");

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() method in Java.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs
Predicate Java Docs

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial