ArrayList removeAll() method

Java ArrayList removeAll() method not removing elements

This sneppet teaches you how to use ArrayList removeAll() method to remove elements from a ArrayList that are specified in a specific collection. Note, you have to override Object’s equals method to make this work.

Example: ArrayList removeAll() method and equals()


public class Person {

	private String id;
	private String name;
	private int age;
	public Person(String id, String name, int age)
	{ = id; = name;
		this.age = age;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public int getAge() {
		return age;
	public void setAge(int age) {
		this.age = age;
	public boolean equals(Object obj)
		if(obj == this)
			return true;
		if(!(obj instanceof Person))
			return false;
		Person p = (Person)obj;

Note, we override equals method, so that we can compare objects for equality. The following is the sample test program which demonstrates ArrayList removeAll() method, which removes from this list of its elements that are contained in the specified collection.


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ArrayListRemoveAllExample {
	public static void main (String[] args)
		List<Person> listOfPersons = new ArrayList<Person>();
		System.out.println("List if Persons Before : " + doPrint(listOfPersons));
		System.out.println("List if Persons After Removal : " + doPrint(listOfPersons));

	private static void createPersonsList(List<Person> listOfPersons) {		
		listOfPersons.add(new Person("101","John", 35));
		listOfPersons.add(new Person("102","Peter", 25));
		listOfPersons.add(new Person("103","Paul", 20));
		listOfPersons.add(new Person("104","Samuel", 45));
		listOfPersons.add(new Person("105","Vincent", 50));
		listOfPersons.add(new Person("106","Werner", 25));
		listOfPersons.add(new Person("107","Robert", 30));		
	private static Collection<?> listOfPersonsToBeRemoved() {
		List<Person> listOfPersonsLTThirty = new ArrayList<Person>();
		listOfPersonsLTThirty.add(new Person("102","Peter", 25));
		listOfPersonsLTThirty.add(new Person("103","Paul", 20));
		listOfPersonsLTThirty.add(new Person("106","Werner", 25));
		return listOfPersonsLTThirty;
	private static String doPrint(List<Person> listOfPersons) {
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<listOfPersons.size(); i++)
			if(i < listOfPersons.size()-1)
		return sb.toString();



List if Persons Before : John,Peter,Paul,Samuel,Vincent,Werner,Robert
List if Persons After Removal : John,Samuel,Vincent,Robert

Further Reading


Notify of

Inline Feedbacks
View all comments