7

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?

1
  • 3
    Can you be more accurate describing your question ? write a snippet of the code you are working on ... Commented May 8, 2012 at 16:02

9 Answers 9

24
Iterator<User> it = list.iterator();
while (it.hasNext()) {
  User user = it.next();
  if (user.getName().equals("John Doe")) {
    it.remove();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't look like the OP did any work for this question, you shouldn't give them code for free.
7

You could use something like this:

           // If you are using java 8
           userList.removeIf(user-> user.getName().equals("yourUserName"));
           // With older version
           User userToRemove = null;
           for(User usr:userList) {
             if(usr.getName().equals("yourUserName")) {
                userToRemove = usr;
                break;
             }
           }
           userList.remove(userToRemove);

5 Comments

What is s? Please make your answers a bit more specific.
s is predicate here and this only works in JDK 1.8 where Lambda expression is supported.Removes all of the elements of this collection that satisfy the given predicate.
This is awesome answer. and easy to understand
Thanks . Your answer helped me a lot to graduate from computer science. I gave you a badge for the best answer after 8 years xD
@MohamedGamal glad to know . Thanks
7

Another thought: If User class can be uniquely defined by the username and if you override equals with something like:

public boolean equals(Object arg0) {
    return this.name.equals(((user) arg0).name);
}

You can remove the User without iterating through the list . You can just do :

 list.remove(new User("John Doe"))

Comments

6

You are probably faced with the ConcurrentModificationException while trying to remove object from the List. An explanation for this exception is that the iterator of the ArrayList is a fail-fast iterator. For example, it will throw an exception (fail) when it detects that its collection in the runtime has been modified. The solution to this problem is to use the Iterator.

Here is a simple example that demonstrate how you could iterate through the List and remove the element when specific condition is met:

List<User> list = new ...

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

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

Comments

6

Recommended way to solve this problem is:

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 remove an object is more efficient than removing by simply typing ArrayList(Object) because it is more faster and 20% more time saving and a standard Java practice for Java Collections.

Comments

3

You could:

  • loop over the list with an iterator
  • check if each item in your list is the right user (checking the name)
  • if it is, use the remove method of the iterator.

Comments

1

Just search through the ArrayList of objects you get from the user, and test for a name equal to the name you want to remove. Then remove that object from the list.

4 Comments

One hopes there are optimizations that can be made, as otherwise the OP is stuck with an O(n) implementation.
@X-Zero In what scenario where you dont know where an object is in a list could you have better than O(n)?
@X-Zero: If all the OP has is an array list, then O(n) is the best he can hope for (element removal alone is O(n)).
... Yes, I know. But it'd be nice if we knew it was sorted (by name), or maybe if it was a hashmap or somesuch.
0

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);
        }
    }
}

4 Comments

You should use an iterator to remove within a loop or you will likely get a ConcurrentModificationException.
@assylias The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. And the for-each loop implicity use the iterator
Try to run this code (sorry for the formatting): List<String> list = new ArrayList<String>(); list.add("a"); for (String s : list) { list.remove(s); } and you should get an exception.
@assylias aha that's right I just thought for-each use the iterator but I ignored the fact that list.remove not the iterator.remove unless for-each can explore the iterator object to do the remove function
-1
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 Comment

Can't remove while iterating through for each stackoverflow.com/questions/223918/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.