Remove item from groovy list
Solution 1
Fildor is right, but if you only want ot remove the first occurence of user
in your list (minus will remove all occurrences), you will probably need something like:
list = list.indexOf( user ).with { idx ->
if( idx > -1 ) {
new ArrayList( list ).with { a ->
a.remove( idx )
a
}
}
else list
}
Solution 2
Have you tried
availableUsers - user
?
Docu: http://groovy.codehaus.org/groovy-jdk/java/util/List.html#minus(java.lang.Object) Haven't got much experience with groovy myself, but that's what I would try.
Solution 3
As mentioned above, the answer depends on whether you wish to remove all occurrences of an item...
myList = ['a','b','c', 'c']
myList -= 'c'
assert myList == ['a','b']
...or just the first instance.
myList = ['a','b','c', 'c']
myList.remove(myList.indexOf('c'))
assert myList == ['a','b','c']
I'm still new to Groovy myself, but one of the underlying principles is that it almost always has a way of making common tasks trivial one-liners. Adding or removing items from a collection would certainly qualify.
drago
Updated on May 17, 2020Comments
-
drago almost 4 years
I am trying to remove an item from groovy list. I've tried following:
List<User> availableUsers = [] availableUsers = workers for (int i = 0; i < availableUsers.size(); i++) { if (availableUsers[i].equals(user)){ availableUsers.drop(i) break } }
I've also tried:
availableUsers.remove(user)
In both cases the list gets emptied. Does anyone have any idea what's going on?
-
Phat H. VU over 10 yearsMinus operator for list is NOT a best choice when you are dealing with large lists and their data is complicated. Refer this : rewoo.wordpress.com/2012/11/19/…
-
Fildor over 10 years@PhatH.VU 1. Make it run, 2. make it run correctly, 3. make it run fast. In exactly that order :D But of course, you are right.