How to remove Duplicate Values from a list in groovy
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() ?
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]
Use unique
def list = ["a", "b", "c", "a", "b", "c"]
println list.unique()
This will print
[a, b, c]
def unique = myList as Set
Converts myList
to a Set
. When you use complex (self-defined classes) make sure you have thought about implementing hashCode()
and equals()
correctly.