我有一个ID列表的集合要保存到数据库中
if(!session.ids)
session.ids = []
session.ids.add(params.id)
Run Code Online (Sandbox Code Playgroud)
我发现这个列表有重复,比如
[1, 2, 4, 9, 7, 10, 8, 6, 6, 5]
Run Code Online (Sandbox Code Playgroud)
然后我想通过应用以下内容删除所有重复项:
session.ids.removeAll{ //some clousure case }
Run Code Online (Sandbox Code Playgroud)
我发现只有这个:
http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html
NIN*_*OOP 66
我不是一个Groovy人,但我相信你可以这样做:
[1, 2, 4, 9, 7, 10, 8, 6, 6, 5].unique { a, b -> a <=> b }
Run Code Online (Sandbox Code Playgroud)
你试过session.ids.unique()吗?
tim*_*tes 43
怎么样:
session.ids = session.ids.unique( false )
Run Code Online (Sandbox Code Playgroud)
更新和
之间的区别:第二个不修改原始列表.希望有所帮助.unique()unique(false)
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]
Run Code Online (Sandbox Code Playgroud)
gur*_*eta 14
使用独特
def list = ["a", "b", "c", "a", "b", "c"]
println list.unique()
Run Code Online (Sandbox Code Playgroud)
这将打印
[a, b, c]
Run Code Online (Sandbox Code Playgroud)
def unique = myList as Set
Run Code Online (Sandbox Code Playgroud)
将'myList'转换为Set.当您使用复杂(自定义类)时,请确保您已正确考虑实现hashCode()和equals().