How to remove an object from an ArrayList in Java?

I have ArrayListone that contains some object, for example User, and each object has the property nameand password. How can I remove only an object Userthat has a specific "name" from it ArrayList?

+5
source share
9 answers
Iterator<User> it = list.iterator();
while (it.hasNext()) {
  User user = it.next();
  if (user.getName().equals("John Doe")) {
    it.remove();
  }
}
+21
source

You probably encounter ConcurrentModificationExceptionwhile trying to remove an object from List. The explanation for this exception is that the iterator ArrayListis a fault tolerant iterator. For example, it will throw a failure when it detects that its collection has been modified at run time. The solution to this problem is to use Iterator.

, , List :

List<User> list = new ...

for (Iterator<User> it = list.iterator(); it.hasNext(); ) {

    User user = it.next();
    if (user.getUserEmail().equals(currentUser.getUserEmail())) {
       it.remove();
    }
}
+5

- :

           arrayList.removeIf(s-> s.getName().contains("yourName"));
+5

: , - :

public boolean equals (Object arg0) {

    return this.name.equals(((user) arg0).name);
}

. :

list.remove( ( "John Doe" ))

+4

:

  • , ( )
  • , .
+2

Recommended solution to this problem:

ArrayList<User> list = new ArrayList<User>();
list.add(new User("user1","password1"));
list.add(new User("user2","password2"));
list.add(new User("user3","password3"));
list.add(new User("user4","password4"));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) 
{
    User user = iter.next();
    if(user.name.equals("user1"))
    {
        //Use iterator to remove this User object.
        iter.remove();
    }
}

Using Iterator to delete an object is more efficient than deleting it with simple input ArrayList(Object)  because it saves time and 20% time and standard Java practice for Java collections.

+2
source

Just search through the ArrayList for the objects that you get from the user and check the name equal to the name you want to delete. Then remove this object from the list.

+1
source

Your code might look like this:

List<User> users = new ArrayList<User>();

public void removeUser(String name){
    for(User user:users){
        if(user.name.equals(name)){
            users.remove(user);
        }
    }
}
0
source
ArrayList<User> userList=new ArrayList<>();
//load data

public void removeUser(String userName){
    for (User user: userList){
        if(user.getName()equals(userName)){
            userList.remove(user);
        }
    }
}
-1
source

All Articles