删除列表中所有重复的整数

RAU*_*HEZ 1 groovy

鉴于名单 [1,2,2,3,5,5,6]

我想完全删除重复的值,并得到: [1,3,6]

如果可能的话,我正在寻找一种具有小于 n^2 复杂性和常规功能的单行解决方案!

我正在使用的当前代码:

def elements = [1,2,2,3,5,5,6]

def occurrences = [:]
elements.each {
    occurrences[it] = occurrences[it] ?: 0
    occurrences[it] += 1
}

elements.findAll{ occurrences[it] == 1 }
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 5

我目前能想到的最好的是:

[1,2,2,3,5,5,6].countBy { it }.findAll { it.value == 1 }.keySet()
Run Code Online (Sandbox Code Playgroud)

或者

[1,2,2,3,5,5,6].countBy { it }.findAll { it.value == 1 }.collect { it.key }
Run Code Online (Sandbox Code Playgroud)

将结果保留为列表

...或者...

[1,2,2,3,5,5,6].countBy { it }.findResults { it.value < 2 ? it.key : null }
Run Code Online (Sandbox Code Playgroud)