Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from groovy list

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?

like image 816
drago Avatar asked Apr 25 '13 10:04

drago


People also ask

How do I remove first item from Groovy List?

1 we can use the methods take() and drop() . With the take() method we get items from the beginning of the List. We pass the number of items we want as an argument to the method. To remove items from the beginning of the List we can use the drop() method.

How do I remove a String in Groovy?

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

How do I remove the last character from a String in Groovy?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do I read a Groovy List?

A List literal is presented as a series of objects separated by commas and enclosed in square brackets. To process the data in a list, we must be able to access individual elements. Groovy Lists are indexed using the indexing operator []. List indices start at zero, which refers to the first element.


2 Answers

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.

like image 149
Fildor Avatar answered Oct 20 '22 22:10

Fildor


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.

like image 35
Jack Whipnert Avatar answered Oct 20 '22 22:10

Jack Whipnert