I know that in Groovy, if
list = [1,2,3,1]
when
list.unique()
with return
[1,2,3]
But if I want to detect duplicate value for duplicate, non-consecutive items in a list. How can I do this?
detect([1,2,3,1]) => true
detect([1,2,3,2]) => true
detect([1,1,2,3]) => false
detect([1,2,2,3,3]) => false
detect([1,2,3,4]) => false
Thanks.
Edit: add these two cases
detect([1,2,2,1]) => true
detect([1,2,1,1]) => true
true means any non-consecutive, duplicate occur.
In case you need to obtain duplicate elements:
def nonUniqueElements = {list ->
list.findAll{a -> list.findAll{b -> b == a}.size() > 1}.unique()
}
assert nonUniqueElements(['a', 'b', 'b', 'c', 'd', 'c']) == ['b', 'c']
This should do it:
List list = ["a", "b", "c", "a", "d", "c", "a"]
and
list.countBy{it}.grep{it.value > 1}.collect{it.key}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With