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?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Mohamed Gamal
  • 145
  • 1
  • 2
  • 12
  • 3
    Can you be more accurate describing your question ? write a snippet of the code you are working on ... – aleroot May 08 '12 at 16:02

9 Answers9

24
Iterator<User> it = list.iterator();
while (it.hasNext()) {
  User user = it.next();
  if (user.getName().equals("John Doe")) {
    it.remove();
  }
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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"))
RubioRic
  • 2,442
  • 4
  • 28
  • 35
hari_sree
  • 1,508
  • 3
  • 12
  • 24
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);
manikant gautam
  • 3,521
  • 1
  • 17
  • 27
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();
    }
}
james.garriss
  • 12,959
  • 7
  • 83
  • 96
miksiii
  • 2,426
  • 26
  • 22
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.

Rahul Raina
  • 3,322
  • 25
  • 30
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.
assylias
  • 321,522
  • 82
  • 660
  • 783
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.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
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);
        }
    }
}
james.garriss
  • 12,959
  • 7
  • 83
  • 96
  • 2
    You should use an iterator to remove within a loop or you will likely get a ConcurrentModificationException. – assylias May 08 '12 at 17:06
  • @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 – Matrix Scarlett Johansson May 08 '12 at 17:22
  • 1
    Try to run this code (sorry for the formatting): `List list = new ArrayList(); list.add("a"); for (String s : list) { list.remove(s); }` and you should get an exception. – assylias May 08 '12 at 17:26
  • @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 – Matrix Scarlett Johansson May 08 '12 at 17:45
-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);
        }
    }
}
Gangaraju
  • 4,406
  • 9
  • 45
  • 77
  • 2
    Can't remove while iterating through for each http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re – Gangaraju Dec 29 '16 at 06:06