Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to remove objects from a List

Tags:

java

I have the following logic to remove inactive users in the system, since we cannot remove a row while iterating on the list. Is there a better way to handle this?

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

for (User user : users) {
  if (!user.isActive()) {
      removeUsers.add(user);
  }
}

users.removeAll(removeUsers);
like image 323
user339108 Avatar asked Sep 22 '10 07:09

user339108


People also ask

How do you remove an object from a list in Python?

To remove items (elements) from a list in Python, use the list functions clear(), pop(), and remove(). You can also delete items with the del statement by specifying a position or range with an index or slice.

How do you remove an object from a list 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.


3 Answers

I realize this is an old question, but it came up in a search I was doing, so others might still be getting here. With Java 8, the easiest way is to use the new "removeIf" method on the Collection class like so:

users.removeIf(user -> !user.isActive());

Easy peasy! It should be noted that, under the covers, the Java code is using Iterator.remove().

Oracle documentation

like image 96
wholladay Avatar answered Oct 17 '22 00:10

wholladay


You could do:

for (int i = users.size()-1; i >= 0; i--) {
  if (!users.get(i).isActive()) {
    users.remove(i);
  }
}
like image 45
Bart Kiers Avatar answered Oct 17 '22 01:10

Bart Kiers


If you use ArrayList, best way is Jeff M's variant. You may also use your variant, but you should consider to use Set (HashSet or IdentityHashSet) intstead of ArrayList for removeUser. For large amount of data it will have better performance.

But for LinkedList best way will be to use Iterator.remove method:

for (Iterator<User> it = users.iterator(); it.hasNext();)
    if (it.next().isActive())
        it.remove();
like image 24
maxkar Avatar answered Oct 17 '22 02:10

maxkar