Groovy remove duplicate from list using unique function

15,686

Solution 1

Use tokenize() instead of split() which returns an ArrayList as compared to split which return a String Array.

def  myStr = "aaaa ; bbbb ; ccccc;"
def myList = myStr.tokenize(";")*.trim()
myList = myList.unique()

or use toList() if you are using split() or cast the String array to a Set.

However, based on the question you want to remove the duplicate items from list but I do not see any duplicate item. If you mean to remove duplicate strings from the list items then use:

myList = myList.unique().collect { it.toSet().join() }

Solution 2

Simple, .split() returns an array, you just need to convert it to a (Groovy) List. Any of the following will make the unique() method work.

def myList = myStr.split(";").collect()

or

def myList = (List)myStr.split(";")

or

def myList = myStr.split(";").toList()

If you cast it to a java.util.Set, it'll only keep unique values!

def myList = (Set)myStr.split(";")

Gotcha: Be careful though, the strings still contain the spaces!

Share:
15,686
Adi Mor
Author by

Adi Mor

QA Group Leader

Updated on June 04, 2022

Comments

  • Adi Mor
    Adi Mor almost 2 years

    I'm using soapui groovy script. I want to remove the duplicate from a list, using the next code:

    def  myStr = "aaaa ; bbbb ; ccccc"
    
    def myList = myStr.split(";")
    
    myList = myList.unique()
    

    but when i tun the code i get exception:

    No signature of method: [Ljava.lang.String;.unique() is applicable for argument types: () values: [] Possible solutions: minus(java.lang.Object), minus(java.lang.Iterable), minus([Ljava.lang.Object;), size(), use([Ljava.lang.Object;), use(java.lang.Class, groovy.lang.Closure)