Reputation: 51
So I have the following list def list = [1, 2, 3, 1, 4]
. Any value that is being duplicated and all of the instances of that value (in this case '1') need to be removed from the list.
The only thing I found is this: def uniqueId = list.unique()
but unfortunately this only removes one of the values of that duplicate and I end up with uniqueId = [1, 2, 3, 4]
and this doesn't exactly help me. I need my final output to be uniqueId = [2, 3, 4]
.
Anyone knows a solution to this?
Upvotes: 1
Views: 158
Reputation: 171084
Interesting!
So we can do this: (comments inline)
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
}
This gives us [2, 3, 4]
Another way is to use countBy()
instead of 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
}
Same result
Upvotes: 2