Return type | Name and parameters |
---|---|
boolean
|
any(Closure predicate)
Iterates over the contents of an iterable, and checks whether a predicate is valid for at least one element. |
Collection
|
asCollection()
Converts this Iterable to a Collection. |
List
|
asList()
Converts this Iterable to a List. |
Object
|
asType(Class clazz)
Converts the given iterable to another type. |
Object
|
average()
Averages the items in an Iterable. |
Object
|
average(Closure closure)
Averages the result of applying a closure to each item of an Iterable. |
BufferedIterator
|
bufferedIterator()
Returns a BufferedIterator that allows examining the next element without
consuming it.
|
List
|
chop(int chopSizes)
Chops the Iterable into pieces, returning lists with sizes corresponding to the supplied chop sizes. |
List
|
collate(int size)
Collates this iterable into sub-lists of length size .
|
List
|
collate(int size, boolean keepRemainder)
Collates this iterable into sub-lists of length size .
|
List
|
collate(int size, int step)
Collates this iterable into sub-lists of length size stepping through the code step
elements for each subList.
|
List
|
collate(int size, int step, boolean keepRemainder)
Collates this iterable into sub-lists of length size stepping through the code step
elements for each sub-list.
|
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. |
List
|
collect(Closure transform)
Iterates through this Iterable transforming each entry into a new value using the transform closure
returning a list of transformed values.
|
Object
|
collect(Object 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 .
|
Map
|
collectEntries()
A variant of collectEntries for Iterable objects using the identity closure as the transform. |
Map
|
collectEntries(Closure transform)
Iterates through this Iterable transforming each item using the transform closure
and returning a map of the resulting transformed entries.
|
Map
|
collectEntries(Map collector)
A variant of collectEntries for Iterables using the identity closure as the transform and a supplied map as the destination of transformed entries. |
Map
|
collectEntries(Map collector, Closure transform)
Iterates through this Iterable transforming each item using the closure as a transformer into a map entry, returning the supplied map with all the transformed entries added to it. |
Map
|
collectEntries(Map collector, Function keyTransform, Function valueTransform)
A variant of collectEntries for Iterables with separate functions for transforming the keys and values. |
Map
|
collectEntries(Function keyTransform, Function valueTransform)
A variant of collectEntries for Iterables with separate functions for transforming the keys and values. |
List
|
collectMany(Closure projection)
Projects each item from a source Iterable to a collection and concatenates (flattens) the resulting collections into a single list. |
Object
|
collectMany(Object 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 Iterable transforming each non-Collection value into a new value using the closure as a transformer. |
Object
|
collectNested(Object collector, Closure transform)
Recursively iterates through this Iterable transforming each non-Collection value into a new value using the transform closure.
|
List
|
combinations()
Finds all combinations of items from the given aggregate of collections. |
List
|
combinations(Closure function)
Finds all combinations of items from the given aggregate of collections, then returns the results of the supplied transform. |
boolean
|
contains(Object item)
Returns true if this iterable contains the item. |
boolean
|
containsAll(Object[] items)
Returns true if this iterable contains all the elements in the specified array. |
Number
|
count(Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this Iterable. |
Number
|
count(Object value)
Counts the number of occurrences of the given value inside this Iterable. |
Object
|
count(Object initialCount, Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this Iterable. |
Map
|
countBy()
Creates a multiset-like map of the collection members. |
Map
|
countBy(Closure closure)
Sorts all collection members into groups determined by the supplied mapping closure and counts the group size. |
boolean
|
disjoint(Iterable right)
Returns true if the intersection of two iterables is empty.
|
Collection
|
drop(int num)
Drops the given number of elements from the head of this Iterable. |
Collection
|
dropRight(int num)
Drops the given number of elements from the tail of this Iterable. |
Collection
|
dropWhile(Closure condition)
Returns a suffix of this Iterable where elements are dropped from the front while the given closure evaluates to true. |
Iterable
|
each(Closure closure)
Iterates through an Iterable, passing each item to the given closure. |
void
|
eachCombination(Closure function)
Applies a function on each combination of the input lists. |
Iterator
|
eachPermutation(Closure closure)
Iterates over all permutations of a collection, running a closure for each iteration. |
Iterable
|
eachWithIndex(Closure closure)
Iterates through an iterable type, passing each item and the item's index (a counter starting at zero) to the given closure. |
boolean
|
every(Closure predicate)
Used to determine if the given predicate closure is valid (i.e. returns true for all items in this iterable).
|
int
|
findIndexOf(Closure condition)
Iterates over the elements of an Iterable and returns the index of the first item that satisfies the condition specified by the closure. |
int
|
findIndexOf(int startIndex, Closure condition)
Iterates over the elements of an Iterable, starting from a specified startIndex, and returns the index of the first item that satisfies the condition specified by the closure. |
List
|
findIndexValues(Closure condition)
Iterates over the elements of an Iterable and returns the index values of the items that match the condition specified in the closure. |
List
|
findIndexValues(Number startIndex, Closure condition)
Iterates over the elements of an Iterable, starting from a specified startIndex, and returns the index values of the items that match the condition specified in the closure. |
int
|
findLastIndexOf(Closure condition)
Iterates over the elements of an Iterable and returns the index of the last item that matches the condition specified in the closure. |
int
|
findLastIndexOf(int startIndex, Closure condition)
Iterates over the elements of an Iterable, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure. |
Object
|
findResult()
Iterates through the Iterable stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Closure condition)
Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Object defaultResult)
Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. |
Object
|
findResult(Object defaultResult, Closure condition)
Iterates through the Iterable calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. |
Collection
|
findResults()
Iterates through the Iterable collecting any non-null results. |
Collection
|
findResults(Closure filteringTransform)
Iterates through the Iterable transforming items using the supplied closure and collecting any non-null results. |
Object
|
first()
Returns the first item from the Iterable. |
Collection
|
flatten()
Flatten an Iterable. |
Collection
|
flatten(boolean flattenOptionals)
Flatten an Iterable. |
Collection
|
flatten(boolean flattenOptionals, Closure flattenUsing)
Flatten an Iterable. |
Collection
|
flatten(Closure flattenUsing)
Flatten an Iterable. |
Collection
|
flattenMany(Closure transform)
Flatten an Iterable. |
Object
|
getAt(int idx)
Support the subscript operator for an Iterable. |
Map
|
groupBy(Closure closure)
Sorts all Iterable members into groups determined by the supplied mapping closure. |
Map
|
groupBy(Object closures)
Sorts all Iterable members into (sub)groups determined by the supplied mapping closures. |
Map
|
groupBy(List closures)
Sorts all Iterable members into (sub)groups determined by the supplied mapping closures. |
Object
|
head()
Returns the first item from the Iterable. |
Map
|
indexed()
Zips an Iterable with indices in (index, value) order. |
Map
|
indexed(int offset)
Zips an Iterable with indices in (index, value) order. |
Collection
|
init()
Returns the items from the Iterable excluding the last item. |
List
|
inits()
Calculates the init values of this Iterable: the first value will be this list of all items from the iterable and the final one will be an empty list, with the intervening values the results of successive applications of init on the items. |
Object
|
inject(Closure closure)
Iterates through the given object, passing the first two elements to the closure. |
Object
|
inject(Object initialValue, Closure closure)
Iterates through the given object, passing in the initial value to the 2-arg closure along with the first item. |
Collection
|
intersect(Iterable right)
Create a Collection composed of the intersection of both iterables. |
Collection
|
intersect(Iterable right, Closure condition)
Create a Collection composed of the intersection of both iterables. |
Collection
|
intersect(Iterable right, Comparator comparator)
Create a Collection composed of the intersection of both iterables. |
boolean
|
isCase(Object switchValue)
'Case' implementation for iterable types which tests if the 'switch' operand is contained in any of the 'case' values. |
boolean
|
isEmpty()
Check whether an Iterable has elements
def items = [1] def iterable = { [ hasNext:{ ! |
String
|
join()
Concatenates the toString() representation of each item from
the Iterable.
|
String
|
join(String separator)
Concatenates the toString() representation of each item from
the Iterable, with the given String as a separator between each item.
|
Object
|
last()
Returns the last item from the Iterable. |
Object
|
max()
Adds max() method to Iterable objects. |
Object
|
max(Closure closure)
Selects the item in the iterable which when passed as a parameter to the supplied closure returns the maximum value. |
Object
|
max(Comparator comparator)
Selects the maximum value found in the Iterable using the given comparator. |
Object
|
min()
Adds min() method to Collection objects. |
Object
|
min(Closure closure)
Selects the item in the iterable which when passed as a parameter to the supplied closure returns the minimum value. |
Object
|
min(Comparator comparator)
Selects the minimum value found in the Iterable using the given comparator. |
Collection
|
minus(Iterable removeMe)
Create a new Collection composed of the elements of the first Iterable minus every occurrence of elements of the given Iterable. |
Collection
|
minus(Iterable removeMe, Closure condition)
Create a new Collection composed of the elements of the first Iterable minus every matching occurrence as determined by the condition closure of elements of the given Iterable. |
Collection
|
minus(Iterable removeMe, Comparator comparator)
Create a new Collection composed of the elements of the first Iterable minus every matching occurrence as determined by the condition comparator of elements of the given Iterable. |
Collection
|
minus(Object removeMe)
Create a new Collection composed of the elements of the first Iterable minus every occurrence of the given element to remove. |
Collection
|
multiply(Number factor)
Create a Collection composed of the elements of this Iterable, repeated a certain number of times. |
Set
|
permutations()
Finds all permutations of an iterable. |
List
|
permutations(Closure function)
Finds all permutations of an iterable, applies a function to each permutation and collects the result into a list. |
Collection
|
plus(Iterable right)
Create a Collection as a union of two iterables. |
Collection
|
plus(Object right)
Create a collection as a union of an Iterable and an Object. |
int
|
size()
Provide the standard Groovy size() method for Iterable .
|
List
|
sort()
Sorts the Collection. |
List
|
sort(boolean mutate)
Sorts the Iterable. |
List
|
sort(boolean mutate, Closure closure)
Sorts this Iterable using the given Closure to determine the correct ordering. |
List
|
sort(boolean mutate, Comparator comparator)
Sorts the Iterable using the given Comparator. |
List
|
sort(Closure closure)
Sorts this Iterable using the given Closure to determine the correct ordering. |
Stream
|
stream()
Returns a sequential Stream with the specified element(s) as its source. |
Object
|
sum()
Sums the items in an Iterable. |
Object
|
sum(Closure closure)
Sums the result of applying a closure to each item of an Iterable. |
Object
|
sum(Object initialValue)
Sums the items in an Iterable, adding the result to some initial value. |
Object
|
sum(Object initialValue, Closure closure)
Sums the result of applying a closure to each item of an Iterable to some initial value. |
Collection
|
tail()
Returns the items from the Iterable excluding the first item. |
List
|
tails()
Calculates the tail values of this Iterable: the first value will be this list of all items from the iterable and the final one will be an empty list, with the intervening values the results of successive applications of tail on the items. |
Collection
|
take(int num)
Returns the first num elements from the head of this Iterable.
|
Collection
|
takeRight(int num)
Returns the last num elements from the tail of this Iterable.
|
Collection
|
takeWhile(Closure condition)
Returns a Collection containing the longest prefix of the elements from this Iterable where each element passed to the given closure evaluates to true. |
List
|
toList()
Convert an Iterable to a List. |
Set
|
toSet()
Convert an Iterable to a Set. |
List
|
toSorted()
Sorts the Iterable. |
List
|
toSorted(Closure closure)
Sorts this Iterable using the given Closure to determine the correct ordering. |
List
|
toSorted(Comparator comparator)
Sorts the Iterable using the given Comparator. |
SpreadMap
|
toSpreadMap()
Creates a spreadable map from this iterable. |
Collection
|
toUnique()
Returns a Collection containing the items from the Iterable but with duplicates removed using the natural ordering of the items to determine uniqueness. |
Collection
|
toUnique(Closure condition)
Returns a Collection containing the items from the Iterable but with duplicates removed. |
Collection
|
toUnique(Comparator comparator)
Returns a Collection containing the items from the Iterable but with duplicates removed. |
Collection
|
union(Iterable right)
Create a Collection composed of the union of both iterables. |
Collection
|
union(Iterable right, Closure condition)
Create a Collection composed of the union of both iterables. |
Collection
|
union(Iterable right, Comparator comparator)
Create a Collection composed of the union of both iterables. |
Map
|
withCollectedKeys(Map collector, Function keyTransform)
Transform Iterable elements into Map entries with values unchanged and keys transformed using the supplied function. |
Map
|
withCollectedKeys(Function keyTransform)
Transform Iterable elements into Map entries with values unchanged and keys transformed using the supplied function. |
Map
|
withCollectedValues(Map collector, Function valueTransform)
Transform Iterable elements into Map entries with keys unchanged and values transformed using the supplied function. |
Map
|
withCollectedValues(Function valueTransform)
Transform Iterable elements into Map entries with keys unchanged and values transformed using the supplied function. |
List
|
withIndex()
Zips an Iterable with indices in (value, index) order. |
List
|
withIndex(int offset)
Zips an Iterable with indices in (value, index) order. |
Iterator
|
zip(Iterable other)
An iterator of all the pairs of two Iterables. |
Iterates over the contents of an iterable, and checks whether a predicate is valid for at least one element.
assert [1, 2, 3].any { it == 2 }
assert ![1, 2, 3].any { it >
3 }
predicate
- the closure predicate used for matchingConverts this Iterable to a Collection. Returns the original argument if it is already a Collection.
Example usage:
assert new HashSet().asCollection() instanceof Collection
Converts this Iterable to a List. Returns the original Iterable if it is already a List.
Example usage:
assert new HashSet().asList() instanceof List
Converts the given iterable to another type.
clazz
- the desired classAverages the items in an Iterable. This is equivalent to invoking the "plus" method on all items in the Iterable and then dividing by the total count using the "div" method for the resulting sum.
assert 3 == [1, 2, 6].average()
Averages the result of applying a closure to each item of an Iterable.
iter.average(closure)
is equivalent to:
iter.collect(closure).average()
.
assert 20 == [1, 3].average { it * 10 } assert 3 == ['to', 'from'].average { it.size() }
closure
- a single parameter closure that returns a (typically) numeric value.Returns a BufferedIterator
that allows examining the next element without
consuming it.
assert new LinkedHashSet([1,2,3,4]).bufferedIterator().with { [head(), toList()] } == [1, [1,2,3,4]]
Chops the Iterable into pieces, returning lists with sizes corresponding to the supplied chop sizes. If the Iterable isn't large enough, truncated (possibly empty) pieces are returned. Using a chop size of -1 will cause that piece to contain all remaining items from the Iterable.
Example usage:
assert [1, 2, 3, 4].chop(1) == [[1]] assert [1, 2, 3, 4].chop(1,-1) == [[1], [2, 3, 4]] assert ('a'..'h').chop(2, 4) == [['a', 'b'], ['c', 'd', 'e', 'f']] assert ['a', 'b', 'c', 'd', 'e'].chop(3) == [['a', 'b', 'c']] assert ['a', 'b', 'c', 'd', 'e'].chop(1, 2, 3) == [['a'], ['b', 'c'], ['d', 'e']] assert ['a', 'b', 'c', 'd', 'e'].chop(1, 2, 3, 3, 3) == [['a'], ['b', 'c'], ['d', 'e'], [], []]
chopSizes
- the sizes for the returned piecesCollates this iterable into sub-lists of length size
.
Example:
def list = [ 1, 2, 3, 4, 5, 6, 7 ] def coll = list.collate( 3 ) assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
size
- the length of each sub-list in the returned listCollates this iterable into sub-lists of length size
. Any remaining elements in
the iterable after the subdivision will be dropped if keepRemainder
is false.
Example:
def list = [ 1, 2, 3, 4, 5, 6, 7 ] def coll = list.collate( 3, false ) assert coll == [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
size
- the length of each sub-list in the returned listkeepRemainder
- if true, any remaining elements are returned as sub-lists. Otherwise they are discardedCollates this iterable into sub-lists of length size
stepping through the code step
elements for each subList.
Example:
def list = [ 1, 2, 3, 4 ] def coll = list.collate( 3, 1 ) assert coll == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ]
size
- the length of each sub-list in the returned liststep
- the number of elements to step through for each sub-listCollates this iterable into sub-lists of length size
stepping through the code step
elements for each sub-list. Any remaining elements in the iterable after the subdivision will be dropped if
keepRemainder
is false.
Example:
def list = [ 1, 2, 3, 4 ] assert list.collate( 2, 2, true ) == [ [ 1, 2 ], [ 3, 4 ] ] assert list.collate( 3, 1, true ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4 ], [ 4 ] ] assert list.collate( 3, 1, false ) == [ [ 1, 2, 3 ], [ 2, 3, 4 ] ]
size
- the length of each sub-list in the returned liststep
- the number of elements to step through for each sub-listkeepRemainder
- if true, any remaining elements are returned as sub-lists. Otherwise they are discardedIterates 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].collect() == [1,2,3]
Iterates through this Iterable transforming each entry into a new value using the transform
closure
returning a list of transformed values.
assert [1,2,3].collect { it * 2 } == [2,4,6]
transform
- the closure used to transform each item of the collectionIterates through this collection transforming each value into a new value using the transform
closure
and adding it to the supplied collector
.
assert [2,4,5,6].collect(new HashSet()) { (int)(it / 2) } == [1,2,3] as Set
collector
- the Collection to which the transformed values are addedtransform
- the closure used to transform each itemA variant of collectEntries for Iterable objects using the identity closure as the transform.
The source Iterable should contain a list of [key, value]
tuples or Map.Entry
objects.
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]
Iterates through this Iterable transforming each item using the 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']Note: When using the list-style of result, the behavior is '
def (key, value) = listResultFromClosure
'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
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 valueA variant of collectEntries for Iterables using the identity closure as the transform and a supplied map as the destination of transformed entries.
collector
- the Map into which the transformed entries are putIterates through this Iterable transforming each item using the closure as a transformer into a map entry, returning the supplied map with all the transformed entries added to it.
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']Note: When using the list-style of result, the behavior is '
def (key, value) = listResultFromClosure
'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
collector
- the Map into which the transformed entries are puttransform
- 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 valueA variant of collectEntries for Iterables with separate functions for transforming the keys and values. The supplied collector map is used as the destination for transformed entries.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala'] assert languages.collectEntries([clojure:7], String::toLowerCase, String::size) == [clojure:7, groovy:6, java:4, kotlin:6, scala:5]
collector
- the Map into which the transformed entries are putkeyTransform
- a function for transforming Iterable elements into keysvalueTransform
- a function for transforming Iterable elements into valuesA variant of collectEntries for Iterables with separate functions for transforming the keys and values.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala'] assert languages.collectEntries(String::toLowerCase, String::size) == [groovy:6, java:4, kotlin:6, scala:5]
keyTransform
- a function for transforming Iterable elements into keysvalueTransform
- a function for transforming Iterable elements into valuesProjects each item from a source Iterable to a collection and concatenates (flattens) the resulting collections into a single list.
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 itemsProjects each item from a source collection to a result collection and concatenates (flattens) the resulting
collections adding them into the collector
.
def animals = ['CAT', 'DOG', 'ELEPHANT'] 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 @groovy.transform.TypeChecked void test() { LinkedHashSet<String> lhs = ['abc','def'].collectMany(new LinkedHashSet<>()){ it.iterator().collect() } assert lhs == ['a','b','c','d','e','f'] as Set<String> } test()
collector
- an initial collection to add the projected items toprojection
- a projecting Closure returning a collection of itemsRecursively iterates through this Iterable 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 }
transform
- the closure used to transform each item of the IterableRecursively iterates through this Iterable transforming each non-Collection value
into a new value using the 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 addedtransform
- the closure used to transform each element of the IterableFinds all combinations of items from the given aggregate of collections.
Example usage:
result = [['a', 'b'], [1, 2, 3]].combinations() assert result == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]
Finds all combinations of items from the given aggregate of collections, then returns the results of the supplied transform.
Example usage:
result = [[2, 3], [4, 5, 6]].combinations { x,y ->
x*y }
assert result == [8, 12, 10, 15, 12, 18]
function
- a closure to be called on each combination (list)Returns true if this iterable contains the item.
item
- an Object to be checked for containment in this iterableReturns true if this iterable contains all the elements in the specified array.
items
- array to be checked for containment in this iterableCounts the number of occurrences which satisfy the given closure from inside this Iterable.
Example usage:
assert [2,4,2,1,3,5,2,4,3].count{ it % 2 == 0 } == 5
closure
- a closure conditionCounts the number of occurrences of the given value inside this Iterable.
Comparison is done using Groovy's == operator (using
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 forCounts the number of occurrences which satisfy the given closure from inside this Iterable.
Example usage:
assert [2,4,2,1,3,5,2,4,3].count(100L){ it % 2 == 0 } == 105L
initialCount
- start counting from this valueclosure
- a closure conditionCreates a multiset-like map of the collection members.
Example usage:
assert [1:2, 2:2, 3:1] == [1,2,1,2,3].countBy()
Sorts all collection members into groups determined by the supplied mapping closure and counts the group size. The closure should return the key that each item should be grouped by. The returned Map will have an entry for each distinct key returned from the closure, with each value being the frequency of items occurring for that group.
Example usage:
assert [0:2, 1:3] == [1,2,3,4,5].countBy { it % 2 }
closure
- a closure mapping items to the frequency keysReturns true
if the intersection of two iterables is empty.
assert [1,2,3].disjoint([3,4,5]) == false
assert [1,2].disjoint([3,4]) == true
right
- an Iterabletrue
if the intersection of two iterables
is empty, false
otherwise.Drops the given number of elements from the head of this Iterable.
def strings = [ 'a', 'b', 'c' ] assert strings.drop( 0 ) == [ 'a', 'b', 'c' ] assert strings.drop( 2 ) == [ 'c' ] assert strings.drop( 5 ) == [] class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.drop(0) == ['a', 'b', 'c'] assert abc.drop(1) == ['b', 'c'] assert abc.drop(3) == [] assert abc.drop(5) == []
num
- the number of elements to drop from this Iterablenum
elements,
or an empty list if it has less than num
elements.Drops the given number of elements from the tail of this Iterable.
def strings = [ 'a', 'b', 'c' ] assert strings.dropRight( 0 ) == [ 'a', 'b', 'c' ] assert strings.dropRight( 2 ) == [ 'a' ] assert strings.dropRight( 5 ) == [] class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.dropRight(0) == ['a', 'b', 'c'] assert abc.dropRight(1) == ['a', 'b'] assert abc.dropRight(3) == [] assert abc.dropRight(5) == []
num
- the number of elements to drop from this Iterablenum
elements,
or an empty list if it has less than num
elements.Returns a suffix of this Iterable where elements are dropped from the front while the given closure evaluates to true.
class HorseIterable implements Iterable{ Iterator iterator() { "horse".iterator() } } def horse = new HorseIterable() assert horse.dropWhile{ it <
'r' } == ['r', 's', 'e'] assert horse.dropWhile{ it<=
'r' } == ['s', 'e']
condition
- the closure that must evaluate to true to continue dropping elementsIterates through an Iterable, passing each item to the given closure.
closure
- the closure applied on each element foundApplies a function on each combination of the input lists.
Example usage:
[[2, 3],[4, 5, 6]].eachCombination { println "Found $it" }
function
- a closure to be called on each combinationIterates 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]]
closure
- the closure to call for each permutationIterates through an iterable type, passing each item and the item's index (a counter starting at zero) to the given closure.
closure
- a Closure to operate on each itemUsed to determine if the given predicate closure is valid (i.e. returns
true
for all items in this iterable).
A simple example for a list:
def list = [3,4,5]
def greaterThanTwo = list.every { it >
2 }
predicate
- the closure predicate used for matchingIterates over the elements of an Iterable and returns the index of the first item that satisfies the condition specified by the closure.
condition
- the matching conditionIterates over the elements of an Iterable, starting from a specified startIndex, and returns the index of the first item that satisfies the condition specified by the closure.
startIndex
- start matching from this indexcondition
- the matching conditionIterates over the elements of an Iterable and returns the index values of the items that match the condition specified in the closure.
condition
- the matching conditionIterates over the elements of an Iterable, starting from a specified startIndex, and returns the index values of the items that match the condition specified in the closure.
startIndex
- start matching from this indexcondition
- the matching conditionIterates over the elements of an Iterable and returns the index of the last item that matches the condition specified in the closure.
condition
- the matching conditionIterates over the elements of an Iterable, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure.
startIndex
- start matching from this indexcondition
- the matching conditionIterates through the Iterable stopping once the first non-null result is found and returning that result. If all results are null, null is returned.
Iterates through the Iterable calling the given closure condition 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.
condition
- a closure that returns a non-null value to indicate that processing should stop and the value should be returnedIterates through the Iterable calling the given closure condition 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:
assert [null, 1, 2].findResult('default') == 1 assert [null, null].findResult('default') == 'default'
defaultResult
- an Object that should be returned if all elements in the iterable are nullIterates through the Iterable calling the given closure condition 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 }
defaultResult
- an Object that should be returned if all closure results are nullcondition
- a closure that returns a non-null value to indicate that processing should stop and the value should be returnedIterates through the Iterable collecting any non-null results.
Example:
assert [1, null, 2, null, 3].findResults() == [1, 2, 3]
Iterates through the Iterable transforming items using the supplied closure and collecting any non-null results.
Example:
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 discardedReturns the first item from the Iterable.
def set = [3, 4, 2] as LinkedHashSet assert set.first() == 3 // check original is unaltered assert set == [3, 4, 2] as SetThe first element returned by the Iterable's iterator is returned. If the Iterable doesn't guarantee a defined order it may appear like a random element is returned.
Flatten an Iterable. This Iterable 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()
Flatten an Iterable. This Iterable and any nested arrays or collections have their contents (recursively) added to the new collection. If flattenOptionals is true, the non-empty optionals are also flattened.
var items = [1..2, [3, [4]], Optional.of(5), Optional.empty()] assert items.flatten() == [1, 2, 3, 4, 5] // boolean param determines whether to flatten optionals (false for legacy behavior) assert items.flatten(true) == [1, 2, 3, 4, 5] assert items.flatten(false) == [1, 2, 3, 4, Optional.of(5), Optional.empty()]
flattenOptionals
- whether to treat an Optional as a container to flattenFlatten an Iterable. This Iterable and any nested arrays, collections, and potentially Optional elements have their contents (recursively) added to a new collection. Non-container elements are leaf elements. If flattenOptionals is false, Optionals are treated as leaf elements, otherwise they are considered as containers to flatten. The flattenUsing transform can be used to modify leaf nodes. If a leaf node represents some other kind of collective type, the supplied closure should yield the contained item or items; otherwise, the closure should just return the (optionally modified) leaf.
var items = ['a'..'b', ['c'], Optional.of('d'), Optional.empty()] var unknown = { it instanceof Optional ? it.orElse('Unknown') : it.toUpperCase() } // by default Optionals are flattened so the ternary in the // 'unknown' closure will never see the optional assert items.flatten(unknown) == ['A', 'B', 'C', 'D'] assert items.flatten(true, unknown) == ['A', 'B', 'C', 'D'] // disable optional flattening and you can provide custom flattening assert items.flatten(false, unknown) == ['A', 'B', 'C', 'd', 'Unknown']
flattenOptionals
- whether to treat an Optional as a container to flatten or a leafflattenUsing
- a closure to determine how to flatten leaf elementsFlatten an Iterable. This Iterable and any nested arrays, collections, or optionals have their contents (recursively) added to a new collection. Non-Array, non-Collection, non-Optional objects are leaf nodes. The flattenUsing transform can be used to modify leaf nodes. If a leaf node represents some other kind of collective type, the supplied closure should yield the contained items; otherwise, the closure should just return the (optionally modified) leaf.
// some examples just transforming the leaf var items = [1..2, [3, [4]]] assert items.flatten(n -> n + 5) == 6..9 assert items.flatten{ 'x' * it } == ['x', 'xx', 'xxx', 'xxxx'] // Here our String is a "container" of day, month, year parts var dates = ['01/02/99', '12/12/23'] assert dates.flatten{ it.split('/') } == [['01', '02', '99'], ['12', '12', '23']] assert dates.flatten{ it.split('/').toList() } == ['01', '02', '99', '12', '12', '23'] // some examples with Maps assert [a:1, b:2].entrySet().flatten{ "$it.key$it.value" } == ['a1', 'b2'] as Set assert [[a:1], [b:2]].flatten{ it.keySet() + it.values() } == ['a', 1, 'b', 2]
flattenUsing
- a closure to determine how to flatten non-Array, non-Collection elementsFlatten an Iterable. This Iterable and any nested arrays, collections or optionals have their contents (recursively) added to a new collection. A transform is applied to any leaf nodes before further flattening.
var items = ["1", "2", "foo", "3", "bar"] var toInt = s -> s.number ? Optional.of(s.toInteger()) : Optional.empty() assert items.flattenMany(toInt) == [1, 2, 3] assert items.flattenMany(String::toList) == ['1', '2', 'f', 'o', 'o', '3', 'b', 'a', 'r'] assert items.flattenMany{ it.split(/[aeiou]/) } == ['1', '2', 'f', '3', 'b', 'r'] assert ['01/02/99', '12/12/23'].flattenMany{ it.split('/') } == ['01', '02', '99', '12', '12', '23']The
flattenMany
method is somewhat similar to the collectMany
method.
While collectMany
works on the basis that the transform closure returns a
collection, flattenMany
can return a collection, array, optional or modified element.
You should use flattenMany
if you need the extra functionality it offers.
Consider using collectMany
if you return only collections in the transform, since
you will have better type inference in static typing scenarios.
transform
- a transform applied to any leaf elementsSupport the subscript operator for an Iterable. Typical usage:
// custom Iterable example: class MyIterable implements Iterable { Iterator iterator() { [1, 2, 3].iterator() } } def myIterable = new MyIterable() assert myIterable[1] == 2 // Set example: def set = [1,2,3] as LinkedHashSet assert set[1] == 2
idx
- an index value (-self.size() <= idx < self.size()) but using -ve index values will be inefficientSorts all Iterable members into groups determined by the supplied mapping closure. The closure should return the key that this item should be grouped by. The returned LinkedHashMap will have an entry for each distinct key returned from the closure, with each value being a list of items for that group.
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 keysSorts all Iterable 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 array of closures is supplied the IDENTITY Closure will be used.
closures
- an array of closures, each mapping entries on keysSorts all Iterable 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.
closures
- a list of closures, each mapping entries on keysReturns the first item from the Iterable.
def set = [3, 4, 2] as LinkedHashSet assert set.head() == 3 // check original is unaltered assert set == [3, 4, 2] as SetThe first element returned by the Iterable's iterator is returned. If the Iterable doesn't guarantee a defined order it may appear like a random element is returned.
Zips an Iterable with indices in (index, value) order.
Example usage:
assert [0: "a", 1: "b"] == ["a", "b"].indexed()
assert ["0: a", "1: b"] == ["a", "b"].indexed().collect { idx, str ->
"$idx: $str" }
Zips an Iterable with indices in (index, value) order.
Example usage:
assert [5: "a", 6: "b"] == ["a", "b"].indexed(5)
assert ["1: a", "2: b"] == ["a", "b"].indexed(1).collect { idx, str ->
"$idx: $str" }
offset
- an index to start fromReturns the items from the Iterable excluding the last item. Leaves the original Iterable unchanged.
def list = [3, 4, 2] assert list.init() == [3, 4] assert list == [3, 4, 2]
Calculates the init values of this Iterable: the first value will be this list of all items from the iterable and the final one will be an empty list, with the intervening values the results of successive applications of init on the items.
assert [1, 2, 3, 4].inits() == [[1, 2, 3, 4], [1, 2, 3], [1, 2], [1], []]
Iterates through the given object, passing the first two elements to the closure. The result is passed back (injected) to the closure along with the third element and so on until all elements have been consumed.
def items = [1, 2, 3, 4] def value = items.inject { acc, val -> acc * val } assert value == 1 * 2 * 3 * 4 items = [['a','b'], ['b','c'], ['d','b']] value = items.inject { acc, val -> acc.intersect(val) } assert value == ['b'] items = ['j', 'o', 'i', 'n'] as Set value = items.inject(String.&plus) assert value == 'join'
closure
- a closureIterates through the given object, 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 further iteration is not possible.
Also known as foldLeft or reduce in functional parlance. Examples:
assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, valVisual representation of the last example above:->
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)
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 valueclosure
- a closureCreate a Collection composed of the intersection of both iterables. Any elements that exist in both iterables are added to the resultant collection. For iterables of custom objects; the objects should implement java.lang.Comparable
assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])By default, Groovy uses a NumberAwareComparator when determining if an element exists in both collections.
right
- an IterableCreate a Collection composed of the intersection of both iterables. Elements from teh first iterable which also occur (according to the comparator closure) in the second iterable are added to the result. 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(java.lang.Object) or Object#equals(java.lang.Object)). If the closure takes two parameters, two items from the Iterator will be passed as arguments, and the closure should return an int value (with 0 indicating the items are deemed equal).
def one = ['a', 'B', 'c', 'd'] def two = ['b', 'C', 'd', 'e'] def compareIgnoreCase = { it.toLowerCase() } assert one.intersect(two, compareIgnoreCase) == ['B', 'c', 'd'] assert two.intersect(one, compareIgnoreCase) == ['b', 'C', 'd']
right
- an Iterablecondition
- a Closure used to determine unique itemsCreate a Collection composed of the intersection of both iterables. Any elements that exist in both iterables are added to the resultant collection. For iterables of custom objects; the objects should implement java.lang.Comparable
assert [3,4] == [1,2,3,4].intersect([3,4,5,6], Comparator.naturalOrder())
right
- an Iterablecomparator
- a Comparator'Case' implementation for iterable types which tests if the 'switch' operand is contained in any of the 'case' values. For example:
Iterable it = {[1,3,5].iterator()} switch( 3 ) { case it: assert true break default: assert false } //GROOVY-7919 assert 1 in it assert 2 !in it
switchValue
- the switch valueCheck whether an Iterable
has elements
def items = [1] def iterable = { [ hasNext:{ !items.isEmpty() }, next:{ items.pop() } ] as Iterator } as Iterable assert !iterable.isEmpty() iterable.iterator().next() assert iterable.isEmpty()
Concatenates the toString()
representation of each item from
the Iterable.
assert [1,2,3].join() == "123"
Concatenates the toString()
representation of each item from
the Iterable, with the given String as a separator between each item.
assert [1,2,3].join(", ") == "1, 2, 3"
separator
- a String separatorReturns the last item from the Iterable.
def set = [3, 4, 2] as LinkedHashSet assert set.last() == 2 // check original unaltered assert set == [3, 4, 2] as SetThe last element returned by the Iterable's iterator is returned. If the Iterable doesn't guarantee a defined order it may appear like a random element is returned.
Adds max() method to Iterable objects.
assert 5 == [2,3,1,5,4].max()
Selects the item in the iterable which when passed as a parameter to the supplied closure returns the maximum value. A null return value represents the least possible return value, so any item for which the supplied closure returns null, won't be selected (unless all items return null). If more than one item has the maximum value, an arbitrary choice is made between the items having the maximum value.
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 "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 orderingSelects the maximum value found in the Iterable using the given comparator.
assert "hello" == ["hello","hi","hey"].max( { a, b->
a.length()<=>
b.length() } as Comparator )
comparator
- a ComparatorAdds min() method to Collection objects.
assert 2 == [4,2,5].min()
Selects the item in the iterable which when passed as a parameter to the supplied closure returns the minimum value. A null return value represents the least possible return value. If more than one item has the minimum value, an arbitrary choice is made between the items having the minimum value.
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" == ["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 orderingSelects the minimum value found in the Iterable using the given comparator.
assert "hi" == ["hello","hi","hey"].min( { a, b->
a.length()<=>
b.length() } as Comparator )
comparator
- a ComparatorCreate a new Collection composed of the elements of the first Iterable minus every occurrence of elements of the given Iterable.
assert [1, "a", true, true, false, 5.3] - [true, 5.3] == [1, "a", false]
removeMe
- an Iterable of elements to removeCreate a new Collection composed of the elements of the first Iterable minus every matching occurrence as determined by the condition closure of elements of the given Iterable.
assert ['a', 'B', 'c', 'D', 'E'].minus(['b', 'C', 'D']) { it.toLowerCase() } == ['a', 'E']
removeMe
- an Iterable of elements to removecondition
- a Closure used to determine unique itemsCreate a new Collection composed of the elements of the first Iterable minus every matching occurrence as determined by the condition comparator of elements of the given Iterable.
assert ['a', 'B', 'c', 'D', 'E'].minus(['b', 'C', 'D'], (i, j) -> i.toLowerCase() <=> j.toLowerCase()
) == ['a', 'E']
removeMe
- an Iterable of elements to removecomparator
- a ComparatorCreate a new Collection composed of the elements of the first Iterable minus every occurrence of the given element to remove.
assert ["a", 5, 5, true] - 5 == ["a", true]
removeMe
- an element to remove from the IterableCreate a Collection composed of the elements of this Iterable, 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] * 2Note: if the Iterable happens to not support duplicates, e.g. a Set, then the method will effectively return a Collection with a single copy of the Iterable's items.
factor
- the number of times to appendFinds all permutations of an iterable.
Example usage:
def result = [1, 2, 3].permutations() assert result == [[3, 2, 1], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2, 1, 3], [1, 2, 3]] as Set
Finds all permutations of an iterable, applies a function to each permutation and collects the result into a list.
Example usage:
Set result = [1, 2, 3].permutations { it.collect { v ->
2*v }}
assert result == [[6, 4, 2], [6, 2, 4], [2, 6, 4], [4, 6, 2], [4, 2, 6], [2, 4, 6]] as Set
function
- the function to apply on each permutationCreate a Collection as a union of two iterables. If the left iterable 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]
right
- the right IterableCreate a collection as a union of an Iterable and an Object. If the iterable 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
right
- an object to add/appendProvide the standard Groovy size()
method for Iterable
.
def items = [1, 2, 3] def iterable = { [ hasNext:{ !items.isEmpty() }, next:{ items.pop() } ] as Iterator } as Iterable assert iterable.size() == 3
Sorts the Collection. Assumes that the collection items are comparable and uses their natural ordering to determine the resulting order. 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.
assert [1,2,3] == [3,1,2].sort()
Sorts the Iterable. Assumes that the Iterable items are comparable and uses their natural ordering to determine the resulting order. If the Iterable is a List and mutate is true, 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 Iterable unchanged.
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 placeSorts this Iterable using the given Closure to determine the correct ordering. If the Iterable is a List and mutate is true, 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 Iterable 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() }
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 placeclosure
- a 1 or 2 arg Closure used to determine the correct orderingSorts the Iterable using the given Comparator. If the Iterable is a List and mutate is true, 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 Iterable unchanged.
assert ["hi","hey","hello"] == ["hello","hi","hey"].sort(false, { 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 placecomparator
- a Comparator used for the comparisonSorts this Iterable using the given Closure to determine the correct ordering. If the Iterable 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 Iterable 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() }
closure
- a 1 or 2 arg Closure used to determine the correct orderingReturns a sequential Stream with the specified element(s) as its source.
class Items implements Iterable{ Iterator<String> iterator() { ['one', 'two'].iterator() } } def items = new Items() assert items.stream().toList() == ['one', 'two']
Sums the items in an Iterable. This is equivalent to invoking the "plus" method on all items in the Iterable.
assert 1+2+3+4 == [1,2,3,4].sum()
Sums the result of applying a closure to each item of an Iterable.
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 (typically) numeric value.Sums the items in an Iterable, adding the result to some initial value.
assert 5+1+2+3+4 == [1,2,3,4].sum(5)
initialValue
- the items in the collection will be summed to this initial valueSums the result of applying a closure to each item of an Iterable to some initial value.
iter.sum(initVal, closure)
is equivalent to:
iter.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 (typically) numeric value.initialValue
- the closure results will be summed to this initial valueReturns the items from the Iterable excluding the first item.
def list = [3, 4, 2] assert list.tail() == [4, 2] assert list == [3, 4, 2]
Calculates the tail values of this Iterable: the first value will be this list of all items from the iterable and the final one will be an empty list, with the intervening values the results of successive applications of tail on the items.
assert [1, 2, 3, 4].tails() == [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4], []]
Returns the first num
elements from the head of this Iterable.
def strings = [ 'a', 'b', 'c' ] assert strings.take( 0 ) == [] assert strings.take( 2 ) == [ 'a', 'b' ] assert strings.take( 5 ) == [ 'a', 'b', 'c' ] class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.take(0) == [] assert abc.take(1) == ['a'] assert abc.take(3) == ['a', 'b', 'c'] assert abc.take(5) == ['a', 'b', 'c']
num
- the number of elements to take from this Iterablenum
elements from this Iterable,
or else all the elements from the Iterable if it has less than num
elements.Returns the last num
elements from the tail of this Iterable.
def strings = [ 'a', 'b', 'c' ] assert strings.takeRight( 0 ) == [] assert strings.takeRight( 2 ) == [ 'b', 'c' ] assert strings.takeRight( 5 ) == [ 'a', 'b', 'c' ] class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.takeRight(0) == [] assert abc.takeRight(1) == ['c'] assert abc.takeRight(3) == ['a', 'b', 'c'] assert abc.takeRight(5) == ['a', 'b', 'c']
num
- the number of elements to take from this Iterablenum
elements from this Iterable,
or else all the elements from the Iterable if it has less than num
elements.Returns a Collection containing the longest prefix of the elements from this Iterable where each element passed to the given closure evaluates to true.
class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.takeWhile{ it <
'b' } == ['a'] assert abc.takeWhile{ it<=
'b' } == ['a', 'b']
condition
- the closure that must evaluate to true to
continue taking elementsConvert an Iterable to a List. The Iterable's iterator will become exhausted of elements after making this conversion.
Example usage:
def x = [1,2,3] as HashSet assert x.class == HashSet assert x.toList() instanceof List
Convert an Iterable to a Set. Always returns a new Set even if the Iterable 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
Sorts the Iterable. Assumes that the Iterable elements are
comparable and uses a NumberAwareComparator to determine the resulting order.
NumberAwareComparator
has special treatment for numbers but otherwise uses the
natural ordering of the Iterable elements. The elements are first placed into a new list which
is then sorted and returned - leaving the original Iterable unchanged.
def orig = [1, 3, 2] def sorted = orig.toSorted() assert orig == [1, 3, 2] assert sorted == [1, 2, 3]
Sorts this Iterable using the given Closure to determine the correct ordering. The elements are first placed into a new list which is then sorted and returned - leaving the original Iterable 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() }
closure
- a 1 or 2 arg Closure used to determine the correct orderingSorts the Iterable using the given Comparator. The elements are first placed into a new list which is then sorted and returned - leaving the original Iterable unchanged.
def orig = ["hello","hi","Hey"] def sorted = orig.toSorted(String.CASE_INSENSITIVE_ORDER) assert orig == ["hello","hi","Hey"] assert sorted == ["hello","Hey","hi"]
comparator
- a Comparator used for the comparisonCreates a spreadable map from this iterable.
Returns a Collection containing the items from the Iterable but with duplicates removed using the natural ordering of the items to determine uniqueness.
String[] letters = ['c', 'a', 't', 's', 'a', 't', 'h', 'a', 't'] String[] expected = ['c', 'a', 't', 's', 'h'] assert letters.toUnique() == expected
Returns a Collection containing the items from the Iterable but with duplicates removed. The items in the Iterable are compared by the given Closure condition. For each duplicate, the first member which is returned from the Iterable is retained, but all other ones are removed.
If the closure takes a single parameter, each element from the Iterable will be passed to the closure. The closure should return a value used for comparison (either using Comparable#compareTo(java.lang.Object) or Object#equals(java.lang.Object)). If the closure takes two parameters, two items from the Iterable will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).
class Person { def fname, lname String toString() { return fname + " " + lname } } 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] def list2 = list.toUnique{ p1, p2->
p1.lname != p2.lname ? p1.lname <=> p2.lname : p1.fname <=> p2.fname } assert( list2 == [a, b, c]&&
list == [a, b, c, d] ) def list3 = list.toUnique{ it.toString() } assert( list3 == [a, b, c]&&
list == [a, b, c, d] )
condition
- a Closure used to determine unique itemsReturns a Collection containing the items from the Iterable but with duplicates removed. The items in the Iterable are compared by the given Comparator. For each duplicate, the first member which is returned from the Iterable is retained, but all other ones are removed.
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.toUnique(new PersonComparator())
assert list2 == [a, b, c] &&
list == [a, b, c, d]
comparator
- a Comparator used to determine unique (equal) items
If null
, the Comparable natural ordering of the elements will be used.Create a Collection composed of the union of both iterables. Any elements that exist in either iterables are added to the resultant collection, such that no elements are duplicated in the resultant collection. For iterables of custom objects; the objects should implement java.lang.Comparable
assert [1,2,3,4,5,6,7,8] == [1,2,3,4,5].union([4,5,6,7,8])By default, Groovy uses a NumberAwareComparator when determining if an element already exists in the resultant collection.
right
- an IterableCreate a Collection composed of the union of both iterables. Elements from the first iterable and second iterable are added to the result if the elements are not already in the result (according to the comparator closure). 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(java.lang.Object) or Object#equals(java.lang.Object)). If the closure takes two parameters, two items from the Iterator will be passed as arguments, and the closure should return an int value (with 0 indicating the items are deemed equal).
def one = ['a', 'B', 'c', 'd'] def two = ['b', 'C', 'd', 'e'] def compareIgnoreCase = { it.toLowerCase() } assert one.union(two, compareIgnoreCase) == ['a', 'B', 'c', 'd', 'e'] assert two.union(one, compareIgnoreCase) == ['b', 'C', 'd', 'e', 'a']
right
- an Iterablecondition
- a Closure used to determine unique itemsCreate a Collection composed of the union of both iterables. Any elements that exist in either iterables are added to the resultant collection, such that no elements are duplicated in the resultant collection. For iterables of custom objects; the objects should implement java.lang.Comparable
assert [1,2,3,4,5,6] == [1,2,3,4].union([3,4,5,6], Comparator.naturalOrder())
right
- an Iterablecomparator
- a ComparatorTransform Iterable elements into Map entries with values unchanged and keys transformed using the supplied function. The supplied map is used as the destination for transformed entries.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
def firstLetter = s ->
s[0]
assert languages.withCollectedKeys([C:'Clojure'], firstLetter) ==
[C:'Clojure', G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
This method is a convenience method for Iterable#collectEntries(Map, Function, Function)
with the valueTransform
replaced by Function.identity()
or {Closure.IDENTITY}.
collector
- the Map into which the transformed entries are putkeyTransform
- a function for transforming Iterator elements into keysTransform Iterable elements into Map entries with values unchanged and keys transformed using the supplied function.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala']
def firstLetter = s ->
s[0]
assert languages.withCollectedKeys(firstLetter) ==
[G:'Groovy', J:'Java', K:'Kotlin', S:'Scala']
This method is a convenience method for Iterable#collectEntries(Function, Function)
with the valueTransform
replaced by Function.identity()
or {Closure.IDENTITY}.
keyTransform
- a function for transforming Iterator elements into keysTransform Iterable elements into Map entries with keys unchanged and values transformed using the supplied function. The supplied collector map is used as the destination for transformed entries.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala'] assert languages.withCollectedValues([Clojure:7], String::size) == [Clojure:7, Groovy:6, Java:4, Kotlin:6, Scala:5]This method is a convenience method for Iterable#collectEntries(Map, Function, Function) with the
keyTransform
replaced by Function.identity()
or {Closure.IDENTITY}.
collector
- the Map into which the transformed entries are putvalueTransform
- a function for transforming Iterable elements into valuesTransform Iterable elements into Map entries with keys unchanged and values transformed using the supplied function.
def languages = ['Groovy', 'Java', 'Kotlin', 'Scala'] assert languages.withCollectedValues(String::size) == [Groovy:6, Java:4, Kotlin:6, Scala:5]This method is a convenience method for Iterable#collectEntries(Function, Function) with the
keyTransform
replaced by Function.identity()
or {Closure.IDENTITY}.
valueTransform
- a function for transforming Iterable elements into valuesZips an Iterable with indices in (value, index) order.
Example usage:
assert [["a", 0], ["b", 1]] == ["a", "b"].withIndex()
assert ["0: a", "1: b"] == ["a", "b"].withIndex().collect { str, idx ->
"$idx: $str" }
Zips an Iterable with indices in (value, index) order.
Example usage:
assert [["a", 5], ["b", 6]] == ["a", "b"].withIndex(5)
assert ["1: a", "2: b"] == ["a", "b"].withIndex(1).collect { str, idx ->
"$idx: $str" }
offset
- an index to start fromAn iterator of all the pairs of two Iterables.
def one = ['cat', 'spider'] def two = ['fish', 'monkey'] assert ['catfish', 'spidermonkey'] == one.zip(two).collect{ a, b -> a + b } assert [one, two].transpose() == one.zip(two).toList()
other
- another Iterable