Groovy JDK

java.util
Class Collection

Method Summary
boolean addAll(Object[] items)
Modifies the collection by adding all of the elements in the specified array to the collection.
boolean asBoolean()
Coerce a collection instance to a boolean value.
Collection asImmutable()
A convenience method for creating an immutable Collection.
Collection asSynchronized()
A convenience method for creating a synchronized Collection.
Object asType(Class clazz)
Converts the given collection to another type.
List collect(Closure transform)
Iterates through this collection transforming each entry into a new value using the transform closure returning a list of transformed values.
List collect()
Iterates through this collection transforming each entry into a new value using Closure.IDENTITY as a transformer, basically returning a list of items copied from the original collection.
Collection collect(Collection collector, Closure transform)
Iterates through this collection transforming each value into a new value using the transform closure and adding it to the supplied collector.
List collectAll(Closure transform)
Deprecated alias for collectNested
Collection collectAll(Collection collector, Closure transform)
Deprecated alias for collectNested
List collectNested(Closure transform)
Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer.
boolean containsAll(Object[] items)
Returns true if this collection contains all of the elements in the specified array.
boolean disjoint(Collection right)
Returns true if the intersection of two collections is empty.
Iterator eachPermutation(Closure closure)
Iterates over all permutations of a collection, running a closure for each iteration.
Object find(Closure closure)
Finds the first value matching the closure condition.
Object find()
Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).
Collection findAll(Closure closure)
Finds all values matching the closure condition.
Collection findAll()
Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).
Object findResult(Object defaultResult, Closure closure)
Iterates through the collection calling the given closure for each item but stopping once the first non-null result is found and returning that result.
Object findResult(Closure closure)
Iterates through the collection calling the given closure for each item but stopping once the first non-null result is found and returning that result.
Collection flatten()
Flatten a collection.
Collection flatten(Closure flattenUsing)
Flatten a collection.
List getAt(String property)
Support the subscript operator for Collection.
Collection grep(Object filter)
Iterates over the collection of items and returns each item that matches the given filter - calling the Object#isCase method used by switch statements.
Collection grep()
Iterates over the collection returning each element that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
Map groupBy(List closures)
Sorts all collection members into (sub)groups determined by the supplied mapping closures.
Object inject(Closure closure)
Performs the same function as the version of inject that takes an initial value, but uses the head of the Collection as the initial value, and iterates over the tail.
Object inject(Object initialValue, Closure closure)
Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item.
Collection intersect(Collection right)
Create a Collection composed of the intersection of both collections.
boolean isCase(Object switchValue)
'Case' implementation for collections which tests if the 'switch' operand is contained in any of the 'case' values.
Collection leftShift(Object value)
Overloads the left shift operator to provide an easy way to append objects to a Collection.
Object min()
Adds min() method to Collection objects.
List multiply(Number factor)
Create a List composed of the elements of this list, repeated a certain number of times.
Collection plus(Collection right)
Create a Collection as a union of two collections.
Collection plus(Iterable right)
Create a Collection as a union of a Collection and an Iterable.
Collection plus(Object right)
Create a collection as a union of a Collection and an Object.
boolean removeAll(Object[] items)
Modifies this collection by removing its elements that are contained within the specified object array.
boolean removeAll(Closure condition)
Modifies this collection by removing the elements that are matched according to the specified closure condition.
boolean retainAll(Object[] items)
Modifies this collection so that it retains only its elements that are contained in the specified array.
boolean retainAll(Closure condition)
Modifies this collection so that it retains only its elements that are matched according to the specified closure condition.
List sort(Closure closure)
Sorts this Collection using the given Closure to determine the correct ordering.
Collection split(Closure closure)
Splits all items into two collections based on the closure condition.
List toList()
Convert a Collection to a List.
String toListString()
Returns the string representation of the given list.
String toListString(int maxSize)
Returns the string representation of the given list.
Set toSet()
Convert a Collection to a Set.
Collection unique()
Modifies this collection to remove all duplicated items, using the default comparator.
Collection unique(boolean mutate)
Remove all duplicates from a given Collection using the default comparator.
Collection unique(Closure closure)
A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
Collection unique(boolean mutate, Closure closure)
A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.
Collection unique(Comparator comparator)
Remove all duplicates from a given Collection.
Collection unique(boolean mutate, Comparator comparator)
Remove all duplicates from a given Collection.
 
Method Detail

addAll

public boolean addAll(Object[] items)
 
Modifies the collection by adding all of the elements in the specified array to the collection. The behavior of this operation is undefined if the specified array is modified while the operation is in progress. See also plus or the '+' operator if wanting to produce a new collection containing additional items but while leaving the original collection unchanged.
Parameters:
items - array containing elements to be added to this collection.
Returns:
true if this collection changed as a result of the call
Since:
1.7.2
See:
Collection#addAll(Collection).

asBoolean

public boolean asBoolean()
 
Coerce a collection instance to a boolean value. A collection is coerced to false if it's empty, and to true otherwise.
assert [1,2].asBoolean() == true
assert [].asBoolean() == false
Returns:
the boolean value
Since:
1.7.0

asImmutable

public Collection asImmutable()
 
A convenience method for creating an immutable Collection.
def mutable = [1,2,3]
def immutable = mutable.asImmutable()
mutable << 4
try {
  immutable << 4
  assert false
} catch (UnsupportedOperationException) {
  assert true
}
Returns:
an immutable Collection
Since:
1.5.0
See:
Collections#unmodifiableCollection.

asSynchronized

public Collection asSynchronized()
 
A convenience method for creating a synchronized Collection.
Returns:
a synchronized Collection
Since:
1.0
See:
Collections#synchronizedCollection.

asType

public Object asType(Class clazz)
 
Converts the given collection to another type. A default concrete type is used for List, Set, or SortedSet. If the given type has a constructor taking a collection, that is used. Otherwise, the call is deferred to {link #asType(Object,Class)}. If this collection is already of the given type, the same instance is returned.
Parameters:
clazz - the desired class.
Returns:
the object resulting from this type conversion
Since:
1.0
See:
Object#asType.

collect

public List collect(Closure transform)
 
Iterates through this collection transforming each entry into a new value using the transform closure returning a list of transformed values.
assert [2,4,6] == [1,2,3].collect { it * 2 }
Parameters:
transform - the closure used to transform each item of the collection.
Returns:
a List of the transformed values
Since:
1.0

collect

public List collect()
 
Iterates through this collection transforming each entry into a new value using Closure.IDENTITY as a transformer, basically returning a list of items copied from the original collection.
assert [1,2,3] == [1,2,3].collect()
Returns:
a List of the transformed values
Since:
1.8.5
See:
Closure#IDENTITY.

collect

public Collection collect(Collection collector, Closure transform)
 
Iterates through this collection transforming each value into a new value using the transform closure and adding it to the supplied collector.
assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }
Parameters:
collector - the Collection to which the transformed values are added.
transform - the closure used to transform each item of the collection.
Returns:
the collector with all transformed values added to it
Since:
1.0

collectAll

public List collectAll(Closure transform)
 
Deprecated alias for collectNested
Parameters:
See:
Collection#collectNested(Closure).

collectAll

public Collection collectAll(Collection collector, Closure transform)
 
Deprecated alias for collectNested
Parameters:
See:
Iterable#collectNested(Collection, Closure).

collectNested

public List collectNested(Closure transform)
 
Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer. Returns a potentially nested list of transformed values.
assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
Parameters:
transform - the closure used to transform each item of the collection.
Returns:
the resultant collection
Since:
1.8.1

containsAll

public boolean containsAll(Object[] items)
 
Returns true if this collection contains all of the elements in the specified array.
Parameters:
items - array to be checked for containment in this collection.
Returns:
true if this collection contains all of the elements in the specified array
Since:
1.7.2
See:
Collection#containsAll(Collection).

disjoint

public boolean disjoint(Collection right)
 
Returns true if the intersection of two collections is empty.
assert [1,2,3].disjoint([3,4,5]) == false
assert [1,2].disjoint([3,4]) == true
Parameters:
right - a Collection.
Returns:
boolean true if the intersection of two collections is empty, false otherwise.
Since:
1.0

eachPermutation

public Iterator eachPermutation(Closure closure)
 
Iterates over all permutations of a collection, running a closure for each iteration.

Example usage:

def permutations = []
[1, 2, 3].eachPermutation{ permutations << it }
assert permutations == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Parameters:
closure - the closure to call for each permutation.
Returns:
the permutations from the list
Since:
1.7.0

find

public Object find(Closure closure)
 
Finds the first value matching the closure condition. Example:
def list = [1,2,3]
assert 2 == list.find { it > 1 }
Parameters:
closure - a closure condition.
Returns:
the first Object found
Since:
1.0

find

public Object find()
 
Finds the first item matching the IDENTITY Closure (i.e. matching Groovy truth).

Example:

def items = [null, 0, 0.0, false, '', [], 42, 43]
assert items.find() == 42
Returns:
the first Object found or null if none was found
Since:
1.8.1
See:
Closure#IDENTITY.

findAll

public Collection findAll(Closure closure)
 
Finds all values matching the closure condition.
assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }
Parameters:
closure - a closure condition.
Returns:
a Collection of matching values
Since:
1.5.6

findAll

public Collection findAll()
 
Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth).

Example:

def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
Returns:
a List of the values found
Since:
1.8.1
See:
Closure#IDENTITY.

findResult

public Object findResult(Object defaultResult, Closure closure)
 
Iterates through the collection calling the given closure for each item but stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned.

Examples:

def list = [1,2,3]
assert "Found 2" == list.findResult("default") { it > 1 ? "Found $it" : null }
assert "default" == list.findResult("default") { it > 3 ? "Found $it" : null }
Parameters:
defaultResult - an Object that should be returned if all closure results are null.
closure - a closure that returns a non-null value when processing should stop and a value should be returned.
Returns:
the first non-null result from calling the closure, or the defaultValue
Since:
1.7.5

findResult

public Object findResult(Closure closure)
 
Iterates through the collection calling the given closure for each item but stopping once the first non-null result is found and returning that result. If all results are null, null is returned.

Example:

def list = [1,2,3]
assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }
Parameters:
closure - a closure that returns a non-null value when processing should stop and a value should be returned.
Returns:
the first non-null result from calling the closure, or null
Since:
1.7.5

flatten

public Collection flatten()
 
Flatten a collection. This collection and any nested arrays or collections have their contents (recursively) added to the new collection.
assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()
Returns:
a flattened Collection
Since:
1.6.0

flatten

public Collection flatten(Closure flattenUsing)
 
Flatten a collection. This collection and any nested arrays or collections have their contents (recursively) added to the new collection. For any non-Array, non-Collection object which represents some sort of collective type, the supplied closure should yield the contained items; otherwise, the closure should just return any element which corresponds to a leaf.
Parameters:
flattenUsing - a closure to determine how to flatten non-Array, non-Collection elements.
Returns:
a flattened Collection
Since:
1.6.0

getAt

public List getAt(String property)
 
Support the subscript operator for Collection.
assert [String, Long, Integer] == ["a",5L,2]["class"]
Parameters:
property - a String.
Returns:
a List
Since:
1.0

grep

public Collection grep(Object filter)
 
Iterates over the collection of items and returns each item that matches the given filter - calling the Object#isCase method used by switch statements. This method can be used with different kinds of filters like regular expressions, classes, ranges etc. Example:
def list = ['a', 'b', 'aa', 'bc', 3, 4.5]
assert list.grep( ~/a+/ )  == ['a', 'aa']
assert list.grep( ~/../ )  == ['aa', 'bc']
assert list.grep( Number ) == [ 3, 4.5 ]
assert list.grep{ it.toString().size() == 1 } == [ 'a', 'b', 3 ]
Parameters:
filter - the filter to perform on each element of the collection (using the Object#isCase method).
Returns:
a collection of objects which match the filter
Since:
2.0

grep

public Collection grep()
 
Iterates over the collection returning each element that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.

Example:

def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null]
assert items.grep() == [1, 2, true, 'foo', [4, 5]]
Returns:
a collection of elements satisfy Groovy truth
Since:
2.0
See:
Closure#IDENTITY.

groupBy

public Map groupBy(List closures)
 
Sorts all collection members into (sub)groups determined by the supplied mapping closures. Each closure should return the key that this item should be grouped by. The returned LinkedHashMap will have an entry for each distinct 'key path' returned from the closures, with each value being a list of items for that 'group path'. Example usage:
def result = [1,2,3,4,5,6].groupBy([{ it % 2 }, { it < 4 }])
assert result == [1:[(true):[1, 3], (false):[5]], 0:[(true):[2], (false):[4, 6]]]
Another example:
def sql = groovy.sql.Sql.newInstance(/* ... */)
def data = sql.rows("SELECT * FROM a_table").groupBy([{ it.column1 }, { it.column2 }, { it.column3 }])
if (data.val1.val2.val3) {
    // there exists a record where:
    //   a_table.column1 == val1
    //   a_table.column2 == val2, and
    //   a_table.column3 == val3
} else {
    // there is no such record
}
If an empty list of closures is supplied the IDENTITY Closure will be used.
Parameters:
closures - a list of closures, each mapping entries on keys.
Returns:
a new Map grouped by keys on each criterion
Since:
1.8.1
See:
Closure#IDENTITY.

inject

public Object inject(Closure closure)
 
Performs the same function as the version of inject that takes an initial value, but uses the head of the Collection as the initial value, and iterates over the tail.
assert 1 * 2 * 3 * 4 == [ 1, 2, 3, 4 ].inject { acc, val -> acc * val }
assert ['b'] == [['a','b'], ['b','c'], ['d','b']].inject { acc, val -> acc.intersect( val ) }
LinkedHashSet set = [ 't', 'i', 'm' ]
assert 'tim' == set.inject { a, b -> a + b }
Parameters:
closure - a closure.
Returns:
the result of the last closure call
Since:
1.8.7
See:
Collection#inject(Object, Closure).

inject

public Object inject(Object initialValue, Closure closure)
 
Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as foldLeft or reduce in functional parlance. Examples:
assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val }

assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val }

assert 'The quick brown fox' ==
    ['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val }

assert 'bat' ==
    ['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min }

def max = { a, b -> [a, b].max() }
def animals = ['bat', 'rat', 'cat']
assert 'rat' == animals.inject('aaa', max)
Visual representation of the last example above:
   initVal  animals[0]
      v        v
max('aaa',   'bat')  =>  'bat'  animals[1]
                           v       v
                     max('bat',  'rat')  =>  'rat'  animals[2]
                                               v       v
                                         max('rat',  'cat')  =>  'rat'
Parameters:
initialValue - some initial value.
closure - a closure.
Returns:
the result of the last closure call
Since:
1.0

intersect

public Collection intersect(Collection right)
 
Create a Collection composed of the intersection of both collections. Any elements that exist in both collections are added to the resultant collection.
assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])
Parameters:
right - a Collection.
Returns:
a Collection as an intersection of both collections
Since:
1.5.6

isCase

public boolean isCase(Object switchValue)
 
'Case' implementation for collections which tests if the 'switch' operand is contained in any of the 'case' values. For example:
switch( 3 ) {
  case [1,3,5]:
    assert true
    break
  default:
    assert false
}
Parameters:
switchValue - the switch value.
Returns:
true if the caseValue is deemed to contain the switchValue
Since:
1.0
See:
Collection#contains.

leftShift

public Collection leftShift(Object value)
 
Overloads the left shift operator to provide an easy way to append objects to a Collection.
def list = [1,2]
list << 3
assert list == [1,2,3]
Parameters:
value - an Object to be added to the collection..
Returns:
same collection, after the value was added to it.
Since:
1.0

min

public Object min()
 
Adds min() method to Collection objects.
assert 2 == [4,2,5].min()
Returns:
the minimum value
Since:
1.0
See:
GroovyCollections#min.

multiply

public List multiply(Number factor)
 
Create a List composed of the elements of this list, repeated a certain number of times. Note that for non-primitive elements, multiple references to the same instance will be added.
assert [1,2,3,1,2,3] == [1,2,3] * 2
Parameters:
factor - the number of times to append.
Returns:
the multiplied list
Since:
1.0

plus

public Collection plus(Collection right)
 
Create a Collection as a union of two collections. If the left collection is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.
assert [1,2,3,4] == [1,2] + [3,4]
Parameters:
right - the right Collection.
Returns:
the merged Collection
Since:
1.5.0

plus

public Collection plus(Iterable right)
 
Create a Collection as a union of a Collection and an Iterable. If the left collection is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.
Parameters:
right - the right Iterable.
Returns:
the merged Collection
Since:
1.8.7
See:
Collection#plus(Collection).

plus

public Collection plus(Object right)
 
Create a collection as a union of a Collection and an Object. If the collection is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.
assert [1,2,3] == [1,2] + 3
Parameters:
right - an object to add/append.
Returns:
the resulting Collection
Since:
1.5.0

removeAll

public boolean removeAll(Object[] items)
 
Modifies this collection by removing its elements that are contained within the specified object array. See also findAll and grep when wanting to produce a new list containing items which don't match some criteria while leaving the original collection unchanged.
Parameters:
items - array containing elements to be removed from this collection.
Returns:
true if this collection changed as a result of the call
Since:
1.7.2
See:
Collection#removeAll(Collection).

removeAll

public boolean removeAll(Closure condition)
 
Modifies this collection by removing the elements that are matched according to the specified closure condition. See also findAll and grep when wanting to produce a new list containing items which don't match some criteria while leaving the original collection unchanged.
Parameters:
condition - a closure condition.
Returns:
true if this collection changed as a result of the call
Since:
1.7.2
See:
Iterator#remove().

retainAll

public boolean retainAll(Object[] items)
 
Modifies this collection so that it retains only its elements that are contained in the specified array. In other words, removes from this collection all of its elements that are not contained in the specified array. See also grep and findAll when wanting to produce a new list containing items which match some specified items but leaving the original collection unchanged.
Parameters:
items - array containing elements to be retained from this collection.
Returns:
true if this collection changed as a result of the call
Since:
1.7.2
See:
Collection#retainAll(Collection).

retainAll

public boolean retainAll(Closure condition)
 
Modifies this collection so that it retains only its elements that are matched according to the specified closure condition. In other words, removes from this collection all of its elements that don't match. See also findAll and grep when wanting to produce a new list containing items which match some criteria but leaving the original collection unchanged.
Parameters:
condition - a closure condition.
Returns:
true if this collection changed as a result of the call
Since:
1.7.2
See:
Iterator#remove().

sort

public List sort(Closure closure)
 
Sorts this Collection using the given Closure to determine the correct ordering. If the Collection is a List, it is sorted in place and returned. Otherwise, the elements are first placed into a new list which is then sorted and returned - leaving the original Collection unchanged.

If the Closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.

assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
Parameters:
closure - a 1 or 2 arg Closure used to determine the correct ordering.
Returns:
a newly created sorted List
Since:
1.0
See:
Collection#sort(boolean, Closure).

split

public Collection split(Closure closure)
 
Splits all items into two collections based on the closure condition. The first list contains all items which match the closure expression. The second list all those that don't.

Example usage:

assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }
Parameters:
closure - a closure condition.
Returns:
a List whose first item is the accepted values and whose second item is the rejected values
Since:
1.6.0

toList

public List toList()
 
Convert a Collection to a List. Always returns a new List even if the Collection is already a List.

Example usage:

def x = [1,2,3] as HashSet
assert x.class == HashSet
assert x.toList() instanceof List
Returns:
a List
Since:
1.0

toListString

public String toListString()
 
Returns the string representation of the given list. The string displays the contents of the list, similar to a list literal, i.e. [1, 2, a].
Returns:
the string representation
Since:
1.0

toListString

public String toListString(int maxSize)
 
Returns the string representation of the given list. The string displays the contents of the list, similar to a list literal, i.e. [1, 2, a].
Parameters:
maxSize - stop after approximately this many characters and append '...'.
Returns:
the string representation
Since:
1.7.3

toSet

public Set toSet()
 
Convert a Collection to a Set. Always returns a new Set even if the Collection is already a Set.

Example usage:

def result = [1, 2, 2, 2, 3].toSet()
assert result instanceof Set
assert result == [1, 2, 3] as Set
Returns:
a Set
Since:
1.8.0

unique

public Collection unique()
 
Modifies this collection to remove all duplicated items, using the default comparator.
assert [1,3] == [1,3,3].unique()
Returns:
the now modified collection
Since:
1.0
See:
Collection#unique(boolean).

unique

public Collection unique(boolean mutate)
 
Remove all duplicates from a given Collection using the default comparator. If mutate is true, it works by modifying the original object (and also returning it). If mutate is false, a new collection is returned leaving the original unchanged.
assert [1,3] == [1,3,3].unique()
def orig = [1, 3, 2, 3]
def uniq = orig.unique(false)
assert orig == [1, 3, 2, 3]
assert uniq == [1, 3, 2]
Parameters:
mutate - false will cause a new list containing unique items from the collection to be created, true will mutate collections in place.
Returns:
the now modified collection
Since:
1.8.1

unique

public Collection unique(Closure closure)
 
A convenience method for making a collection unique using a Closure to determine duplicate (equal) items.

If the closure takes a single parameter, the argument passed will be each element, and the closure should return a value used for comparison (either using Comparable#compareTo or Object#equals). If the closure takes two parameters, two items from the collection will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).

assert [1,4] == [1,3,4,5].unique { it % 2 }
assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }
Parameters:
closure - a 1 or 2 arg Closure used to determine unique items.
Returns:
self without any duplicates
Since:
1.0
See:
Collection#unique(boolean, Closure).

unique

public Collection unique(boolean mutate, Closure closure)
 
A convenience method for making a collection unique using a Closure to determine duplicate (equal) items. If mutate is true, it works on the receiver object and returns it. If mutate is false, a new collection is returned.

If the closure takes a single parameter, the argument passed will be each element, and the closure should return a value used for comparison (either using Comparable#compareTo or Object#equals). If the closure takes two parameters, two items from the collection will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).

def orig = [1, 3, 4, 5]
def uniq = orig.unique(false) { it % 2 }
assert orig == [1, 3, 4, 5]
assert uniq == [1, 4]
def orig = [2, 3, 3, 4]
def uniq = orig.unique(false) { a, b -> a <=> b }
assert orig == [2, 3, 3, 4]
assert uniq == [2, 3, 4]
Parameters:
mutate - false will always cause a new list to be created, true will mutate lists in place.
closure - a 1 or 2 arg Closure used to determine unique items.
Returns:
self without any duplicates
Since:
1.8.1

unique

public Collection unique(Comparator comparator)
 
Remove all duplicates from a given Collection. Works on the original object (and also returns it). The order of members in the Collection are compared by the given Comparator. For each duplicate, the first member which is returned by the given Collection's iterator is retained, but all other ones are removed. The given Collection's original order is preserved.

class Person {
    def fname, lname
    String toString() {
        return fname + " " + lname
    }
}

class PersonComparator implements Comparator {
    int compare(Object o1, Object o2) {
        Person p1 = (Person) o1
        Person p2 = (Person) o2
        if (p1.lname != p2.lname)
            return p1.lname.compareTo(p2.lname)
        else
            return p1.fname.compareTo(p2.fname)
    }

    boolean equals(Object obj) {
        return this.equals(obj)
    }
}

Person a = new Person(fname:"John", lname:"Taylor")
Person b = new Person(fname:"Clark", lname:"Taylor")
Person c = new Person(fname:"Tom", lname:"Cruz")
Person d = new Person(fname:"Clark", lname:"Taylor")

def list = [a, b, c, d]
List list2 = list.unique(new PersonComparator())
assert( list2 == list && list == [a, b, c] )
Parameters:
comparator - a Comparator.
Returns:
self the now modified collection without duplicates
Since:
1.0
See:
Collection#unique.

unique

public Collection unique(boolean mutate, Comparator comparator)
 
Remove all duplicates from a given Collection. If mutate is true, it works on the original object (and also returns it). If mutate is false, a new collection is returned. The order of members in the Collection are compared by the given Comparator. For each duplicate, the first member which is returned by the given Collection's iterator is retained, but all other ones are removed. The given Collection's original order is preserved.

class Person {
    def fname, lname
    String toString() {
        return fname + " " + lname
    }
}

class PersonComparator implements Comparator {
    int compare(Object o1, Object o2) {
        Person p1 = (Person) o1
        Person p2 = (Person) o2
        if (p1.lname != p2.lname)
            return p1.lname.compareTo(p2.lname)
        else
            return p1.fname.compareTo(p2.fname)
    }

    boolean equals(Object obj) {
        return this.equals(obj)
    }
}

Person a = new Person(fname:"John", lname:"Taylor")
Person b = new Person(fname:"Clark", lname:"Taylor")
Person c = new Person(fname:"Tom", lname:"Cruz")
Person d = new Person(fname:"Clark", lname:"Taylor")

def list = [a, b, c, d]
List list2 = list.unique(false, new PersonComparator())
assert( list2 != list && list2 == [a, b, c] )
Parameters:
mutate - false will always cause a new collection to be created, true will mutate collections in place.
comparator - a Comparator.
Returns:
self the collection without duplicates
Since:
1.8.1

Groovy JDK