|
Groovy JDK |
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. |
List
|
asList()
Converts this Collection to a List. |
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 |
Map
|
collectEntries(Closure transform)
Iterates through this Collection transforming each item using the transform closure
and returning a map of the resulting transformed entries.
|
Map
|
collectEntries()
A variant of collectEntries using the identity closure as the transform. |
Map
|
collectEntries(Map collector, Closure transform)
Iterates through this Collection transforming each item using the closure as a transformer into a map entry, returning a map of the transformed entries. |
Map
|
collectEntries(Map collector)
A variant of collectEntries using the identity closure as the transform. |
List
|
collectMany(Closure projection)
Projects each item from a source collection to a collection and concatenates (flattens) the resulting collections into a single list. |
Collection
|
collectMany(Collection collector, Closure projection)
Projects each item from a source collection to a result collection and concatenates (flattens) the resulting collections adding them into the collector .
|
List
|
collectNested(Closure transform)
Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer. |
Collection
|
collectNested(Collection collector, Closure transform)
Recursively iterates through this collection transforming each non-Collection value into a new value using the transform closure.
|
List
|
combinations()
Adds GroovyCollections#combinations(Collection) as a method on collections. |
boolean
|
containsAll(Object[] items)
Returns true if this collection contains all of the elements in the specified array. |
Number
|
count(Object value)
Counts the number of occurrences of the given value inside this collection. |
Number
|
count(Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this collection. |
Map
|
countBy(Closure closure)
Sorts all collection members into groups determined by the supplied mapping closure and counts the group size. |
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. |
Collection
|
findAll(Closure closure)
Finds all values matching the closure condition. |
Collection
|
findAll()
Finds the items matching the IDENTITY Closure (i.e. |
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
|
findResults(Closure filteringTransform)
Iterates through the collection transforming items using the supplied closure and collecting any non-null results. |
Collection
|
flatten()
Flatten a collection. |
Collection
|
flatten(Closure flattenUsing)
Flatten a collection. |
List
|
getAt(String property)
Support the subscript operator for Collection. |
Map
|
groupBy(Closure closure)
Sorts all collection members into groups determined by the supplied mapping closure. |
Map
|
groupBy(Object closures)
Sorts all collection members into (sub)groups determined by the supplied mapping closures. |
Map
|
groupBy(List closures)
Sorts all collection members into (sub)groups determined by the supplied mapping closures. |
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. |
String
|
join(String separator)
Concatenates the toString() representation of each
item in this collection, with the given String as a separator between
each item.
|
Collection
|
leftShift(Object value)
Overloads the left shift operator to provide an easy way to append objects to a Collection. |
Object
|
max()
Adds max() method to Collection objects. |
Object
|
max(Closure closure)
Selects an item in the collection having the maximum value as determined by the supplied closure. |
Object
|
max(Comparator comparator)
Selects the maximum value found in the collection using the given comparator. |
Object
|
min()
Adds min() method to Collection objects. |
Object
|
min(Comparator comparator)
Selects the minimum value found in the collection using the given comparator. |
Object
|
min(Closure closure)
Selects an item in the collection having the minimum value as determined by the supplied closure. |
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(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()
Sorts the Collection. |
List
|
sort(boolean mutate)
Sorts the Collection. |
List
|
sort(Comparator comparator)
Sorts the Collection using the given Comparator. |
List
|
sort(boolean mutate, Comparator comparator)
Sorts the Collection using the given Comparator. |
List
|
sort(Closure closure)
Sorts this Collection using the given Closure to determine the correct ordering. |
List
|
sort(boolean mutate, 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. |
Object
|
sum()
Sums the items in a collection. |
Object
|
sum(Object initialValue)
Sums the items in a collection, adding the result to some initial value. |
Object
|
sum(Closure closure)
Sums the result of apply a closure to each item of a collection. |
Object
|
sum(Object initialValue, Closure closure)
Sums the result of applying a closure to each item of a collection to some initial value. |
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 |
---|
public boolean addAll(Object[] items)
plus
or the '+' operator if wanting to produce a new collection
containing additional items but while leaving the original collection unchanged.items
- array containing elements to be added to this collection.public boolean asBoolean()
assert [1,2].asBoolean() == true
assert [].asBoolean() == false
public Collection asImmutable()
def mutable = [1,2,3] def immutable = mutable.asImmutable() mutable << 4 try { immutable << 4 assert false } catch (UnsupportedOperationException) { assert true }
public List asList()
Example usage:
assert new HashSet().asList() instanceof List
public Collection asSynchronized()
public Object asType(Class clazz)
clazz
- the desired class.public List collect(Closure transform)
transform
closure
returning a list of transformed values.
assert [2,4,6] == [1,2,3].collect { it * 2 }
transform
- the closure used to transform each item of the collection.public List collect()
assert [1,2,3] == [1,2,3].collect()
public Collection collect(Collection collector, Closure transform)
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) }
collector
- the Collection to which the transformed values are added.transform
- the closure used to transform each item of the collection.public List collectAll(Closure transform)
public Collection collectAll(Collection collector, Closure transform)
public Map collectEntries(Closure transform)
transform
closure
and returning a map of the resulting transformed entries.
def letters = "abc" // collect letters with index using list style assert (0..2).collectEntries { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] // collect letters with index using map style assert (0..2).collectEntries { index -> [(index): letters[index]] } == [0:'a', 1:'b', 2:'c']
transform
- the closure used for transforming, which has an item from self as the parameter and
should return a Map.Entry, a Map or a two-element list containing the resulting key and value.public Map collectEntries()
[key, value]
tuples or a Map.Entry
.
def nums = [1, 10, 100, 1000] def tuples = nums.collect{ [it, it.toString().size()] } assert tuples == [[1, 1], [10, 2], [100, 3], [1000, 4]] def map = tuples.collectEntries() assert map == [1:1, 10:2, 100:3, 1000:4]
public Map collectEntries(Map collector, Closure transform)
def letters = "abc" // collect letters with index assert (0..2).collectEntries( [:] ) { index -> [index, letters[index]] } == [0:'a', 1:'b', 2:'c'] assert (0..2).collectEntries( [4:'d'] ) { index -> [(index+1): letters[index]] } == [1:'a', 2:'b', 3:'c', 4:'d']
collector
- the Map into which the transformed entries are put.transform
- the closure used for transforming, which has an item from self as the parameter and
should return a Map.Entry, a Map or a two-element list containing the resulting key and value.public Map collectEntries(Map collector)
collector
- the Map into which the transformed entries are put.public List collectMany(Closure projection)
def nums = 1..10 def squaresAndCubesOfEvens = nums.collectMany{ it % 2 ? [] : [it**2, it**3] } assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216, 64, 512, 100, 1000] def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set def smallAnimals = animals.collectMany{ it.size() > 3 ? [] : [it.toLowerCase()] } assert smallAnimals == ['cat', 'dog'] def orig = nums as Set def origPlusIncrements = orig.collectMany{ [it, it+1] } assert origPlusIncrements.size() == orig.size() * 2 assert origPlusIncrements.unique().size() == orig.size() + 1
projection
- a projecting Closure returning a collection of items.public Collection collectMany(Collection collector, Closure projection)
collector
.
def animals = ['CAT', 'DOG', 'ELEPHANT'] as Set def smallAnimals = animals.collectMany(['ant', 'bee']){ it.size() > 3 ? [] : [it.toLowerCase()] } assert smallAnimals == ['ant', 'bee', 'cat', 'dog'] def nums = 1..5 def origPlusIncrements = nums.collectMany([] as Set){ [it, it+1] } assert origPlusIncrements.size() == nums.size() + 1
collector
- an initial collection to add the projected items to.projection
- a projecting Closure returning a collection of items.public List collectNested(Closure transform)
assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectNested { it * 2 }
transform
- the closure used to transform each item of the collection.public Collection collectNested(Collection collector, Closure transform)
transform
closure. Returns a potentially nested
collection of transformed values.
def x = [1,[2,3],[4],[]].collectNested(new Vector()) { it * 2 } assert x == [2,[4,6],[8],[]] assert x instanceof Vector
collector
- an initial Collection to which the transformed values are added.transform
- the closure used to transform each element of the collection.public List combinations()
Example usage:
assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
public boolean containsAll(Object[] items)
items
- array to be checked for containment in this collection.public Number count(Object value)
compareTo(value) == 0
or equals(value)
).
Example usage:
assert [2,4,2,1,3,5,2,4,3].count(4) == 2
value
- the value being searched for.public Number count(Closure closure)
Example usage:
assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5
closure
- a closure condition.public Map countBy(Closure closure)
Example usage:
assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }
closure
- a closure mapping items to the frequency keys.public boolean disjoint(Collection right)
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
right
- a Collection.true
if the intersection of two collections
is empty, false
otherwise.public Iterator eachPermutation(Closure closure)
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]]
closure
- the closure to call for each permutation.public Object find(Closure closure)
def list = [1,2,3] assert 2 == list.find { it > 1 }
closure
- a closure condition.public Object find()
def items = [null, 0, 0.0, false, '', [], 42, 43] assert items.find() == 42
public Collection findAll(Closure closure)
assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }
closure
- a closure condition.public Collection findAll()
def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.findAll() == [1, 2, true, 'foo', [4, 5]]
public Object findResult(Object defaultResult, Closure closure)
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 }
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.public Object findResult(Closure closure)
def list = [1,2,3] assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }
closure
- a closure that returns a non-null value when processing should stop and a value should be returned.public Collection findResults(Closure filteringTransform)
def list = [1,2,3] def result = list.findResults { it > 1 ? "Found $it" : null } assert result == ["Found 2", "Found 3"]
filteringTransform
- a Closure that should return either a non-null transformed value or null for items which should be discarded.public Collection flatten()
assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()
public Collection flatten(Closure flattenUsing)
flattenUsing
- a closure to determine how to flatten non-Array, non-Collection elements.public List getAt(String property)
assert [String, Long, Integer] == ["a",5L,2]["class"]
property
- a String.public Map groupBy(Closure closure)
Example usage:
assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }
closure
- a closure mapping entries on keys.public Map groupBy(Object closures)
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 array of closures is supplied the IDENTITY Closure will be used.
closures
- an array of closures, each mapping entries on keys.public Map groupBy(List closures)
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.
closures
- a list of closures, each mapping entries on keys.public Object inject(Object initialValue, Closure closure)
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'
initialValue
- some initial value.closure
- a closure.public Collection intersect(Collection right)
assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])
right
- a Collection.public boolean isCase(Object switchValue)
switch( 3 ) { case [1,3,5]: assert true break default: assert false }
switchValue
- the switch value.public String join(String separator)
toString()
representation of each
item in this collection, with the given String as a separator between
each item.
assert "1, 2, 3" == [1,2,3].join(", ")
separator
- a String separator.public Collection leftShift(Object value)
def list = [1,2] list << 3 assert list == [1,2,3]
value
- an Object to be added to the collection..public Object max()
assert 5 == [2,3,1,5,4].max()
public Object max(Closure closure)
assert "hello" == ["hello","hi","hey"].max { it.length() }
assert "hello" == ["hello","hi","hey"].max { a, b -> a.length() <=> b.length() }
def pets = ['dog', 'elephant', 'anaconda'] def longestName = pets.max{ it.size() } // one of 'elephant' or 'anaconda' assert longestName.size() == 8
closure
- a 1 or 2 arg Closure used to determine the correct ordering.public Object max(Comparator comparator)
assert "hello" == ["hello","hi","hey"].max( { a, b -> a.length() <=> b.length() } as Comparator )
comparator
- a Comparator.public Object min()
assert 2 == [4,2,5].min()
public Object min(Comparator comparator)
assert "hi" == ["hello","hi","hey"].min( { a, b -> a.length() <=> b.length() } as Comparator )
comparator
- a Comparator.public Object min(Closure closure)
assert "hi" == ["hello","hi","hey"].min { it.length() }
def lastDigit = { a, b -> a % 10 <=> b % 10 } assert [19, 55, 91].min(lastDigit) == 91
def pets = ['dog', 'cat', 'anaconda'] def shortestName = pets.min{ it.size() } // one of 'dog' or 'cat' assert shortestName.size() == 3
closure
- a 1 or 2 arg Closure used to determine the correct ordering.public List multiply(Number factor)
assert [1,2,3,1,2,3] == [1,2,3] * 2
factor
- the number of times to append.public Collection plus(Collection right)
assert [1,2,3,4] == [1,2] + [3,4]
right
- the right Collection.public Collection plus(Object right)
assert [1,2,3] == [1,2] + 3
right
- an object to add/append.public boolean removeAll(Object[] items)
findAll
and grep
when wanting to produce a new list
containing items which don't match some criteria while leaving the original collection unchanged.items
- array containing elements to be removed from this collection.public boolean removeAll(Closure condition)
findAll
and grep
when wanting to produce a new list
containing items which don't match some criteria while leaving the original collection unchanged.condition
- a closure condition.public boolean retainAll(Object[] items)
grep
and findAll
when wanting to produce a new list
containing items which match some specified items but leaving the original collection unchanged.items
- array containing elements to be retained from this collection.public boolean retainAll(Closure condition)
findAll
and grep
when wanting to produce a new list
containing items which match some criteria but leaving the original collection unchanged.condition
- a closure condition.public List sort()
assert [1,2,3] == [3,1,2].sort()
public List sort(boolean mutate)
assert [1,2,3] == [3,1,2].sort()
def orig = [1, 3, 2] def sorted = orig.sort(false) assert orig == [1, 3, 2] assert sorted == [1, 2, 3]
mutate
- false will always cause a new list to be created, true will mutate lists in place.public List sort(Comparator comparator)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
assert ["hello","Hey","hi"] == ["hello","hi","Hey"].sort(String.CASE_INSENSITIVE_ORDER)
comparator
- a Comparator used for the comparison.public List sort(boolean mutate, Comparator comparator)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort( { a, b -> a.length() <=> b.length() } as Comparator )
def orig = ["hello","hi","Hey"] def sorted = orig.sort(false, String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","hi","Hey"] assert sorted == ["hello","Hey","hi"]
mutate
- false will always cause a new list to be created, true will mutate lists in place.comparator
- a Comparator used for the comparison.public List sort(Closure closure)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
closure
- a 1 or 2 arg Closure used to determine the correct ordering.public List sort(boolean mutate, Closure closure)
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }
def orig = ["hello","hi","Hey"] def sorted = orig.sort(false) { it.toUpperCase() } assert orig == ["hello","hi","Hey"] assert sorted == ["hello","Hey","hi"]
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 the correct ordering.public Collection split(Closure closure)
Example usage:
assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }
closure
- a closure condition.public Object sum()
assert 1+2+3+4 == [1,2,3,4].sum()
public Object sum(Object initialValue)
assert 5+1+2+3+4 == [1,2,3,4].sum(5)
initialValue
- the items in the collection will be summed to this initial value.public Object sum(Closure closure)
coll.sum(closure)
is equivalent to:
coll.collect(closure).sum()
.
assert 4+6+10+12 == [2,3,5,6].sum() { it * 2 }
closure
- a single parameter closure that returns a numeric value..public Object sum(Object initialValue, Closure closure)
coll.sum(initVal, closure)
is equivalent to:
coll.collect(closure).sum(initVal)
.
assert 50+4+6+10+12 == [2,3,5,6].sum(50) { it * 2 }
closure
- a single parameter closure that returns a numeric value..initialValue
- the closure results will be summed to this initial value.public List toList()
Example usage:
def x = [1,2,3] as HashSet assert x.class == HashSet assert x.toList() instanceof List
public String toListString()
[1, 2, a]
.public String toListString(int maxSize)
[1, 2, a]
.maxSize
- stop after approximately this many characters and append '...'.public Set toSet()
Example usage:
def result = [1, 2, 2, 2, 3].toSet() assert result instanceof Set assert result == [1, 2, 3] as Set
public Collection unique()
assert [1,3] == [1,3,3].unique()
public Collection unique(boolean mutate)
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]
mutate
- false will cause a new list containing unique items from the collection to be created, true will mutate collections in place.public Collection unique(Closure closure)
assert [1,4] == [1,3,4,5].unique { it % 2 }
assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }
closure
- a 1 or 2 arg Closure used to determine unique items.public Collection unique(boolean mutate, Closure closure)
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]
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.public Collection unique(Comparator comparator)
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] )
comparator
- a Comparator.public Collection unique(boolean mutate, Comparator comparator)
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] )
mutate
- false will always cause a new collection to be created, true will mutate collections in place.comparator
- a Comparator.
|
Groovy JDK |