Groovy: the simplest way to detect duplicate, non-consecutive values in a list
This should do it:
List list = ["a", "b", "c", "a", "d", "c", "a"]
and
list.countBy{it}.grep{it.value > 1}.collect{it.key}
To determine whether a collection contains non-unique items (your first two examples), you can do something like this:
def a = [1, 2, 3, 1]
boolean nonUnique = a.clone().unique().size() != a.size()
(Note that unique()
modifies the list).
Meanwhile, Collection.unique()
seems to do what you asked as far as 'grouping' items (your last three examples).
Edit: unique()
works properly regardless of whether the collection is sorted.
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']