[java] How to remove specific object from ArrayList in Java?

How can I remove specific object from ArrayList? Suppose I have a class as below:

import java.util.ArrayList;    
public class ArrayTest {
    int i;

    public static void main(String args[]){
        ArrayList<ArrayTest> test=new ArrayList<ArrayTest>();
        ArrayTest obj;
        obj=new ArrayTest(1);
        test.add(obj);
        obj=new ArrayTest(2);
        test.add(obj);
        obj=new ArrayTest(3);
        test.add(obj);
    }
    public ArrayTest(int i){
        this.i=i;
    }
}

How can I remove object with new ArrayTest(1) from my ArrayList<ArrayList>

This question is related to java arraylist

The answer is


Here is full example. we have to use Iterator's remove() method

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayTest {
    int i;
    public static void main(String args[]) {
        ArrayList<ArrayTest> test = new ArrayList<ArrayTest>();
        ArrayTest obj;
        obj = new ArrayTest(1);
        test.add(obj);
        obj = new ArrayTest(2);
        test.add(obj);
        obj = new ArrayTest(3);
        test.add(obj);
        System.out.println("Before removing size is " + test.size() + " And Element are : " + test);
        Iterator<ArrayTest> itr = test.iterator();
        while (itr.hasNext()) {
            ArrayTest number = itr.next();
            if (number.i == 1) {
                itr.remove();
            }
        }
        System.out.println("After removing size is " + test.size() + " And Element are :" + test);
    }
    public ArrayTest(int i) {
        this.i = i;
    }
    @Override
    public String toString() {
        return "ArrayTest [i=" + i + "]";
    }

}

Working demo Screen


    ArrayTest obj=new ArrayTest(1);
    test.add(obj);
    ArrayTest obj1=new ArrayTest(2);
    test.add(obj1);
    ArrayTest obj2=new ArrayTest(3);
    test.add(obj2);

    test.remove(object of ArrayTest);

you can specify how you control each object.


AValchev is right. A quicker solution would be to parse all elements and compare by an unique property.

String property = "property to delete";

for(int j = 0; j < i.size(); j++)
{
    Student obj = i.get(j);

    if(obj.getProperty().equals(property)){
       //found, delete.
        i.remove(j);
        break;
    }

}

THis is a quick solution. You'd better implement object comparison for larger projects.


In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).

In this particular scenario: Add an equals(Object) method to your ArrayTest class. That will allow ArrayList.remove(Object) to identify the correct object.


or you can use java 8 lambda

test.removeIf(i -> i==2);

it will simply remove all object that meet the condition


For removing the particular object from arrayList there are two ways. Call the function of arrayList.

  1. Removing on the basis of the object.
arrayList.remove(object);

This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.

  1. Removing on the basis of specified index position of arrayList. The best way to remove any item or object from arrayList. First, find the index of the item which you want to remove. Then call this arrayList method, this method removes the item on index basis. And it will give the correct result.
arrayList.remove(index);  

You can use Collections.binarySearch to find the element, then call remove on the returned index.

See the documentation for Collections.binarySearch here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.

This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.


List<Object> list = new ArrayList();
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
  Object obj= iterator.next();
    if (obj.getId().equals("1")) {
       // Remove the current element from the iterator and the list.
       iterator.remove();
    }
}

simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)


I have tried this and it works for me:

ArrayList<cartItem> cartItems= new ArrayList<>();

//filling the cartItems

cartItem ci=new cartItem(itemcode,itemQuantity);//the one I want to remove

Iterator<cartItem> itr =cartItems.iterator();
while (itr.hasNext()){
   cartItem ci_itr=itr.next();
   if (ci_itr.getClass() == ci.getClass()){
      itr.remove();
      return;
    }
}

use this code

test.remove(test.indexOf(obj));

test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.

If you are using Java 8:

test.removeIf(t -> t.i == 1);

Java 8 has a removeIf method in the collection interface. For the ArrayList, it has an advanced implementation (order of n).


If you want to remove multiple objects that are matching to the property try this.

I have used following code to remove element from object array it helped me.

In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).

some time for you arrayList.remove(index)or arrayList.remove(obj.get(index)) using these lines may not work try to use following code.

for (Iterator<DetailInbox> iter = detailInboxArray.iterator(); iter.hasNext(); ) {
    DetailInbox element = iter.next();
   if (element.isSelected()) {
      iter.remove();
   }
}

This helped me:

        card temperaryCardFour = theDeck.get(theDeck.size() - 1);
        theDeck.remove(temperaryCardFour);    

instead of

theDeck.remove(numberNeededRemoved);

I got a removal conformation on the first snippet of code and an un removal conformation on the second.

Try switching your code with the first snippet I think that is your problem.

Nathan Nelson