在Array-groovy脚本中查找重复条目



我有一个groovy脚本问题。我正在尝试运行一个脚本,指出数组中的重复条目,并将重复条目放入新的数组中

def i = 0
def j = 1
def result = []
def result2 = []
def list = [1,2,3,4,5,6,7,8,9,10,10,10]
while ( i < list.size) {
while ( j < list.size ) {

if(list[j] == list[i]) {

result.add(list[j])

} else {
j++
}
}

i++
}
log.info ("While iteration ${result}")
def x = 1
for ( a in list) {
while(x < list.size) {
if ( a == list[x]) {
result.add[x]
} 
x++
}
}
log.info ("For iteration ${result2}")

我试着用";而";以及";对于(列表中的(";之间的迭代,但我没能创建重复的数组。

我不希望使用unique((函数来使用相反的方法,因为它会删除重复的内容,而这不是我想要的

如果您想获得重复的值,可以使用:

def list = [1,2,3,4,5,4,5,5,5,5,6,7,8,9,10,10,10]
def duplicateEntries = list.countBy { it }
.findAll { it.value > 1 }
.collectMany { [it.key] * (it.value - 1) }
assert duplicateEntries == [4, 5, 5, 5, 5, 10, 10]

或者,如果你只是想知道他们是谁,那么:

def duplicateEntries = list.countBy { it }.findAll { it.value > 1 }*.key
assert duplicateEntries == [4, 5, 10]

最新更新