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);
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.
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.
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
You could do:
for (int i = users.size()-1; i >= 0; i--) {
if (!users.get(i).isActive()) {
users.remove(i);
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With