How to remove Duplicate Values from a list in groovy

How about:

session.ids = session.ids.unique( false )

Update
Differentiation between unique() and unique(false) : the second one does not modify the original list. Hope that helps.

def originalList = [1, 2, 4, 9, 7, 10, 8, 6, 6, 5]

//Mutate the original list
def newUniqueList = originalList.unique()
assert newUniqueList == [1, 2, 4, 9, 7, 10, 8, 6, 5]
assert originalList  == [1, 2, 4, 9, 7, 10, 8, 6, 5]

//Add duplicate items to the original list again
originalList << 2 << 4 << 10

// We added 2 to originalList, and they are in newUniqueList too! This is because
// they are the SAME list (we mutated the originalList, and set newUniqueList to
// represent the same object.
assert originalList == newUniqueList

//Do not mutate the original list
def secondUniqueList = originalList.unique( false )
assert secondUniqueList == [1, 2, 4, 9, 7, 10, 8, 6, 5]
assert originalList     == [1, 2, 4, 9, 7, 10, 8, 6, 5, 2, 4, 10]

I am not a Groovy person , but I believe you can do something like this :

[1, 2, 4, 9, 7, 10, 8, 6, 6, 5].unique { a, b -> a <=> b }

Have you tried session.ids.unique() ?


Use unique

def list = ["a", "b", "c", "a", "b", "c"]
println list.unique()

This will print

[a, b, c]

Tags:

Groovy