Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove an object from an ArrayList in Java?

Tags:

java

arraylist

I have an ArrayList that contains some object, such as User, and each object has a name and password property. How can I delete only the User object that has a specific 'name' from this ArrayList?

like image 443
Mohamed Gamal Avatar asked May 08 '12 16:05

Mohamed Gamal


People also ask

How can we remove an object from ArrayList while iterating?

The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.

How do you remove an object in Java?

The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List.

How do I remove an object from a collection in Java?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.


1 Answers

Iterator<User> it = list.iterator();
while (it.hasNext()) {
  User user = it.next();
  if (user.getName().equals("John Doe")) {
    it.remove();
  }
}
like image 76
NPE Avatar answered Oct 07 '22 23:10

NPE