如何在groovy中从列表中删除重复值

dgiusagp  于 2022-12-26  发布在  其他
关注(0)|答案(6)|浏览(291)

我收集了一份身份证清单要保存到数据库中

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

lg40wkob

lg40wkob1#

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

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

您是否尝试过session.ids.unique()?

kgsdhlau

kgsdhlau2#

不如这样:

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]
7y4bm7vi

7y4bm7vi3#

使用唯一

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

这将打印

[a, b, c]
7gyucuyw

7gyucuyw4#

def unique = myList as Set

myList转换为Set。使用复杂(自定义类)时,请确保已考虑正确实现hashCode()equals()

yshpjwxd

yshpjwxd5#

如果希望session.ids包含唯一的id,则可以执行以下操作:

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

当你这么做的时候:

session.ids.add(params.id)

将不添加重复项。
您还可以使用以下语法:

session.ids << params.id
6yoyoihd

6yoyoihd6#

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

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]

相关问题