53

我有一组要保存到数据库中的 ID 列表

if(!session.ids)
session.ids = []

session.ids.add(params.id) 

我发现该列表有重复项,例如

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

然后我想通过应用以下内容删除所有重复项:

session.ids.removeAll{ //some clousure case }

我发现只有这个:

http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html

4

6 回答 6

78

我不是一个 Groovy 的人,但我相信你可以做这样的事情:

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

你试过session.ids.unique()吗?

于 2013-07-04T08:50:59.217 回答
53

怎么样:

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

更新和之间的
区别:第二个不修改原始列表。希望有帮助。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]
于 2013-07-04T08:47:52.500 回答
18

使用独特的

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

这将打印

[a, b, c]
于 2013-08-20T22:45:12.680 回答
10
def unique = myList as Set

转换myListSet. 当您使用复杂的(自定义类)时,请确保您已经考虑过实现hashCode()equals()正确。

于 2013-07-04T09:36:50.830 回答
1

如果想要 session.ids 包含唯一的 id,那么你可以这样做:

if(!session.ids)
  session.ids = [] as Set

那么当你这样做时:

session.ids.add(params.id)

不会添加重复项。

您也可以使用以下语法:

session.ids << params.id
于 2016-06-15T19:58:35.103 回答
1

合并两个数组并使元素唯一:

def arr1 = [1,2,3,4]
def arr2 = [1,2,5,6,7,8]
def arr3 = [1,5,6,8,9]

让我们看看合并:

arr1.addAll(arr2, arr3) 
// [1, 2, 3, 4, [1, 2, 5, 6, 7, 8], [1, 5, 6, 8, 9]]
def combined = arr1.flatten() 
// [1, 2, 3, 4, 1, 2, 5, 6, 7, 8, 1, 5, 6, 8, 9]
def combined = arr1.flatten().unique()
// [1, 2, 3, 4, 5, 6, 7, 8, 9]


def combined = (arr1 + arr2 + arr3).flatten().unique()

def combined = (arr1 << arr2 << arr3).flatten().unique()

def combined = arr1.plus(arr2).plus(arr3).flatten().unique()

输出将是:

println combined
[1, 2, 3, 4, 5, 6, 7, 8, 9]
于 2020-11-20T08:22:48.370 回答