Groovy:我需要删除列表中重复的值的所有实例

Groovy: I need to remove all instances of a value that is duplicated in a list

所以我有以下列表 def list = [1, 2, 3, 1, 4]。任何被复制的值以及该值的所有实例(在本例中为“1”)都需要从列表中删除。

我唯一发现的是:def uniqueId = list.unique() 但不幸的是,这只会删除该副本的一个值,我最终得到 uniqueId = [1, 2, 3, 4],这对我没有帮助。我需要我的最终输出是 uniqueId = [2, 3, 4].

有人知道解决这个问题的方法吗?

有趣!

所以我们可以这样做:(内联评论)

def result = list.groupBy() // This will give us a map [1:[1, 1], 2:[2], 3:[3], 4:[4]]
    .findResults {
        // if there is only one entry, return the key
        // Otherwise, return null (so nothing is added to the result)
        it.value.size() == 1 ? it.key : null
    }

这给了我们 [2, 3, 4]

另一种方法是使用 countBy() 而不是 groupBy():

def result = list.countBy { it } // This will give us a map [1:2, 2:1, 3:1, 4:1]
    .findResults {
        // if the value is 1, return the key
        // Otherwise, return null (so nothing is added to the result)
        it.value == 1 ? it.key : null
    }

同样的结果