|
Groovy JDK |
Method Summary | |
---|---|
List
|
asList()
Converts this Iterable to a List. |
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()
A variant of collectEntries for Iterable objects using the identity closure as the transform. |
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 of the transformed entries added to it. |
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. |
List
|
collectMany(Closure projection)
Projects each item from a source Iterable 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 Iterable 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 Iterable transforming each non-Collection value into a new value using the transform closure.
|
List
|
combinations()
Adds GroovyCollections#combinations(Iterable) as a method on Iterables. |
List
|
combinations(Closure function)
Adds GroovyCollections#combinations(Iterable, Closure) as a method on collections. |
Number
|
count(Object value)
Counts the number of occurrences of the given value inside this Iterable. |
Number
|
count(Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this Iterable. |
Map
|
countBy(Closure closure)
Sorts all collection members into groups determined by the supplied mapping closure and counts the group size. |
List
|
drop(int num)
Drops the given number of elements from the head of this Iterable. |
List
|
dropWhile(Closure condition)
Returns a suffix of this Iterable where elements are dropped from the front while the given closure evaluates to true. |
void
|
eachCombination(Closure function)
Applies a function on each combination of the input lists. |
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(Closure flattenUsing)
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. |
String
|
join(String separator)
Concatenates the toString() representation of each
item in this 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 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 Iterable using the given comparator. |
Object
|
min()
Adds min() method to Collection objects. |
Object
|
min(Comparator comparator)
Selects the minimum value found in the Iterable 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
|
sort()
Sorts the Collection. |
List
|
sort(boolean mutate)
Sorts the Iterable. |
List
|
sort(Comparator comparator)
Sorts the Iterable using the given Comparator. |
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. |
List
|
sort(boolean mutate, Closure closure)
Sorts this Iterable using the given Closure to determine the correct ordering. |
Object
|
sum()
Sums the items in an Iterable. |
Object
|
sum(Object initialValue)
Sums the items in an Iterable, adding the result to some initial value. |
Object
|
sum(Closure closure)
Sums the result of apply a closure to each item of an Iterable. |
Object
|
sum(Object initialValue, Closure closure)
Sums the result of applying a closure to each item of an Iterable to some initial value. |
List
|
take(int num)
Returns the first num elements from the head of this Iterable.
|
List
|
takeWhile(Closure condition)
Returns a List 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. |
Method Detail |
---|
public List asList()
Example usage:
assert new HashSet().asList() instanceof List
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 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]
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 Iterable.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 Iterable.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 List combinations(Closure function)
Example usage:
assert [[2, 3],[4, 5, 6]].combinations {x,y -> x*y } == [8, 12, 10, 15, 12, 18]
function
- a closure to be called on each combination.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 List drop(int num)
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 Iterable.num
elements,
or an empty list if it has less then num
elements.public List dropWhile(Closure condition)
class AbcIterable implements Iterable{ Iterator iterator() { "abc".iterator() } } def abc = new AbcIterable() assert abc.dropWhile{ it < 'b' } == ['b', 'c'] assert abc.dropWhile{ it <= 'b' } == ['c']
condition
- the closure that must evaluate to true to continue dropping elements.public void eachCombination(Closure function)
Example usage:
[[2, 3],[4, 5, 6]].eachCombination { println "Found $it" }
function
- a closure to be called on each combination.public Collection findResults(Closure filteringTransform)
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 discarded.public Object first()
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.
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 Object getAt(int idx)
// 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 inefficient.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)
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)
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 String join(String separator)
toString()
representation of each
item in this Iterable, with the given String as a separator between each item.
assert "1, 2, 3" == [1,2,3].join(", ")
separator
- a String separator.public Object last()
def set = [3, 4, 2] as LinkedHashSet assert set.last() == 2 // check original 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.
public Object max()
assert 5 == [2,3,1,5,4].max()
public Object max(Closure closure)
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 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)
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 ordering.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)
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 ordering.public List sort(boolean mutate, Closure closure)
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 place.closure
- a 1 or 2 arg Closure used to determine the correct ordering.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 take(int num)
num
elements from the head of this Iterable.
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 Iterable.num
elements from this Iterable,
or else all the elements from the Iterable if it has less then num
elements.public List takeWhile(Closure condition)
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 elements.public List toList()
|
Groovy JDK |