Overview | Package | Class | Tree | Deprecated | Index | Help
| Groovy JDK

## java.util
Class Collection

Method Summary
`boolean` | `addAll(Object[] items)` Adds all of the elements in the specified array to this 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 closure)` Iterates through this collection transforming each entry into a new value using the closure as a transformer, returning a list of transformed values.
`Collection` | `collect(Collection collection, Closure closure)` Iterates through this collection transforming each value into a new value using the closure as a transformer, returning an initial collection plus the transformed values.
`List` | `collectAll(Closure closure)` Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer.
`Collection` | `collectAll(Collection collection, Closure closure)` Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer.
`Map` | `collectEntries(Map result, Closure closure)` 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(Closure closure)` Iterates through this Collection transforming each item using the closure as a transformer into a map entry, returning a map of the transformed entries.
`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.
`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.
`Collection` | `findAll(Closure closure)` Finds all values matching the closure condition.
`Object` | `findResult(Object defaultResult, Closure closure)` Iterates through the object and returns the first non-null result from the closure, if all are null, it returns the defaultResult.
`Object` | `findResult(Closure closure)` Iterates through the object and returns the first non-null result from the closure.
`Collection` | `flatten()` Flatten a collection.
`Collection` | `flatten(Closure flattenUsing)` Flatten a collection.
`List` | `getAt(String property)` Support the subscript operator for List
    assert [String, Long, Integer] == ["a",5L,2]["class"]
`Map` | `groupBy(Closure closure)` Sorts all collection members into groups determined by the supplied mapping closure.
`Object` | `inject(Object value, 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)` Removes all of this collection's elements that are also contained in the specified array.
`boolean` | `removeAll(Closure closure)` Removes the elements in this collection that are matched according to the specified closure condition.
`boolean` | `retainAll(Object[] items)` Retains only the elements in this collection that are contained in the specified array.
`boolean` | `retainAll(Closure closure)` Retains only the elements in this collection that are matched according to the specified closure condition.
`List` | `sort()` Sorts the given collection into a sorted list.
`List` | `sort(Comparator comparator)` Sorts the Collection using the given comparator.
`List` | `sort(Closure closure)` Sorts this Collection using the 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.
`Collection` | `unique()` Modifies this collection to remove all duplicated items, 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(Comparator comparator)` Remove all duplicates from a given Collection.

Method Detail

### addAll

    public boolean addAll(Object[] items)

  Adds all of the elements in the specified array to this collection. The behavior of this operation is undefined if the specified array is modified while the operation is in progress.

Parameters:

Returns:
  `true` if this collection changed as a result of the call

Since:
  1.7.2

See:
  Collection#addAll(Collection).

### asBoolean

    public boolean asBoolean()

  Coerce a collection instance to a boolean value. A collection is coerced to false if it's empty, and to true otherwise.

      assert [1,2].asBoolean() == true

      assert [].asBoolean() == false

Returns:
  the boolean value

Since:
  1.7.0

### asImmutable

    public Collection asImmutable()

  A convenience method for creating an immutable Collection.

      def mutable = [1,2,3]
      def immutable = mutable.asImmutable()
      mutable << 4
      try {
        immutable << 4
        assert false
      } catch (UnsupportedOperationException) {
        assert true
      }

Returns:
  an immutable Collection

Since:
  1.5.0

See:
  Collections#unmodifiableCollection.

### asList

    public List asList()

  Converts this Collection to a List. Returns the original Collection if it is already a List.

  Example usage:

      assert new HashSet().asList() instanceof List

Returns:
  a newly created List if this collection is not already a List

Since:
  1.0

### asSynchronized

    public Collection asSynchronized()

  A convenience method for creating a synchronized Collection.

Returns:
  a synchronized Collection

Since:
  1.0

See:
  Collections#synchronizedCollection.

### asType

    public Object asType(Class clazz)

  Converts the given collection to another type. A default concrete type is used for List, Set, or SortedSet. If the given type has a constructor taking a collection, that is used. Otherwise, the call is deferred to {link #asType(Object,Class)}. If this collection is already of the given type, the same instance is returned.

Parameters:
  `clazz` - the desired class.

Returns:
  the object resulting from this type conversion

Since:
  1.0

See:
  Object#asType.

### collect

    public List collect(Closure closure)

  Iterates through this collection transforming each entry into a new value using the closure as a transformer, returning a list of transformed values.

      assert [2,4,6] == [1,2,3].collect { it * 2 }

Parameters:
  `closure` - the closure used for mapping.

Returns:
  a List of the transformed values

Since:
  1.0

### collect

    public Collection collect(Collection collection, Closure closure)

  Iterates through this collection transforming each value into a new value using the closure as a transformer, returning an initial collection plus the transformed values.

      assert [1,2,3] as HashSet == [2,4,5,6].collect(new HashSet()) { (int)(it / 2) }

Parameters:
  `collection` - an initial Collection to which the transformed values are added.
  `closure` - the closure used to transform each element of the collection.

Returns:
  the resulting collection of transformed values

Since:
  1.0

### collectAll

    public List collectAll(Closure closure)

  Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer. Returns a potentially nested list of transformed values.

      assert [2,[4,6],[8],[]] == [1,[2,3],[4],[]].collectAll { it * 2 }

Parameters:
  `closure` - the closure used to transform each element of the collection.

Returns:
  the resultant collection

Since:
  1.5.2

### collectAll

    public Collection collectAll(Collection collection, Closure closure)

  Recursively iterates through this collection transforming each non-Collection value into a new value using the closure as a transformer. Returns a potentially nested collection of transformed values.

      def x = [1,[2,3],[4],[]].collectAll(new Vector()) { it * 2 }
      assert x == [2,[4,6],[8],[]]
      assert x instanceof Vector

Parameters:
  `collection` - an initial Collection to which the transformed values are added.
  `closure` - the closure used to transform each element of the collection.

Returns:
  the resultant collection

Since:
  1.5.2

### collectEntries

    public Map collectEntries(Map result, Closure closure)

  Iterates through this Collection transforming each item using the closure as a transformer into a map entry, returning a map of the transformed entries.

      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']

Parameters:
  `result` - the Map into which the collected entries are put.
  `closure` - the closure used for mapping, 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.

Returns:
  a Map of the transformed entries

Since:
  1.7.9

See:
  Map#collect(Collection, Closure).

### collectEntries

    public Map collectEntries(Closure closure)

  Iterates through this Collection transforming each item using the closure as a transformer into a map entry, returning a map of the 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']

Parameters:
  `closure` - the closure used for mapping, 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.

Returns:
  a Map of the transformed entries

Since:
  1.7.9

See:
  Collection#collectEntries(Map, Closure).

### combinations

    public List combinations()

  Adds GroovyCollections#combinations(Collection) as a method on collections.

      assert [['a', 'b'],[1, 2, 3]].combinations() == [['a', 1], ['b', 1], ['a', 2], ['b', 2], ['a', 3], ['b', 3]]

Returns:
  a List of the combinations found

Since:
  1.5.0

See:
  GroovyCollections#combinations.

### containsAll

    public boolean containsAll(Object[] items)

  Returns `true` if this collection contains all of the elements in the specified array.

Parameters:

Returns:
  `true` if this collection contains all of the elements in the specified array

Since:
  1.7.2

See:
  Collection#containsAll(Collection).

### count

    public Number count(Object value)

  Counts the number of occurrences of the given value inside this collection. Comparison is done using Groovy's == operator (using `compareTo(value) == 0` or `equals(value)` ).

      assert [2,4,2,1,3,5,2,4,3].count(4) == 2

Parameters:
  `value` - the value being searched for.

Returns:
  the number of occurrences

Since:
  1.0

### disjoint

    public boolean disjoint(Collection right)

  Returns `true` if the intersection of two collections is empty.

      assert [1,2,3].disjoint([3,4,5]) == false

      assert [1,2].disjoint([3,4]) == true

Parameters:
  `right` - a Collection.

Returns:
  boolean `true` if the intersection of two collections is empty, `false` otherwise.

Since:
  1.0

### eachPermutation

    public Iterator eachPermutation(Closure closure)

  Iterates over all permutations of a collection, running a closure for each iteration.

      def permutations = []
      [1, 2, 3].eachPermutation{ permutations << it }
      assert permutations == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Parameters:
  `closure` - the closure to call for each permutation.

Returns:
  the permutations from the list

Since:
  1.7.0

### find

    public Object find(Closure closure)

  Finds the first value matching the closure condition. Example:

      def list = [1,2,3]
      assert 2 == list.find { it > 1 }

Parameters:
  `closure` - a closure condition.

Returns:
  the first Object found

Since:
  1.0

### findAll

    public Collection findAll(Closure closure)

  Finds all values matching the closure condition.

      assert [2,4] == [1,2,3,4].findAll { it % 2 == 0 }

Parameters:
  `closure` - a closure condition.

Returns:
  a Collection of matching values

Since:
  1.5.6

### findResult

    public Object findResult(Object defaultResult, Closure closure)

  Iterates through the object and returns the first non-null result from the closure, if all are null, it returns the defaultResult. Examples:

      def list = [1,2,3]
      assert "Found 2" == list.findResult("default") { it > 1 ? "Found $it" : null }

      assert "default" == list.findResult("default") { it > 3 ? "Found $it" : null }

Parameters:
  `defaultResult` - an Object that should be returned if all closure results are null.
  `closure` - a closure that returns a non-null value when processing should stop and a value should be returned.

Returns:
  the first non-null result of the closure

Since:
  1.7.5

### findResult

    public Object findResult(Closure closure)

  Iterates through the object and returns the first non-null result from the closure. Example:

      def list = [1,2,3]
      assert "Found 2" == list.findResult { it > 1 ? "Found $it" : null }

Parameters:
  `closure` - a closure that returns a non-null value when processing should stop and a value should be returned.

Returns:
  the first non-null result of the closure

Since:
  1.7.5

### flatten

    public Collection flatten()

  Flatten a collection. This collection and any nested arrays or collections have their contents (recursively) added to the new collection.

      assert [1,2,3,4,5] == [1,[2,3],[[4]],[],5].flatten()

Returns:
  a flattened Collection

Since:
  1.6.0

### flatten

    public Collection flatten(Closure flattenUsing)

  Flatten a collection. This collection and any nested arrays or collections have their contents (recursively) added to the new collection. For any non-Array, non-Collection object which represents some sort of collective type, the supplied closure should yield the contained items; otherwise, the closure should just return any element which corresponds to a leaf.

Parameters:
  `flattenUsing` - a closure to determine how to flatten non-Array, non-Collection elements.

Returns:
  a flattened Collection

Since:
  1.6.0

### getAt

    public List getAt(String property)

  Support the subscript operator for List

      assert [String, Long, Integer] == ["a",5L,2]["class"]

Parameters:
  `property` - a String.

Returns:
  a List

Since:
  1.0

### groupBy

    public Map groupBy(Closure closure)

  Sorts all collection 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.

      assert [0:[2,4,6], 1:[1,3,5]] == [1,2,3,4,5,6].groupBy { it % 2 }

Parameters:
  `closure` - a closure mapping entries on keys.

Returns:
  a new Map grouped by keys

Since:
  1.0

### inject

    public Object inject(Object value, Closure closure)

  Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as `foldLeft` in functional parlance.

Parameters:
  `value` - a value.
  `closure` - a closure.

Returns:
  the last value of the last iteration

Since:
  1.0

### intersect

    public Collection intersect(Collection right)

  Create a Collection composed of the intersection of both collections. Any elements that exist in both collections are added to the resultant collection.

      assert [4,5] == [1,2,3,4,5].intersect([4,5,6,7,8])

Parameters:
  `right` - a Collection.

Returns:
  a Collection as an intersection of both collections

Since:
  1.5.6

### isCase

    public boolean isCase(Object switchValue)

  'Case' implementation for collections which tests if the 'switch' operand is contained in any of the 'case' values. For example:

      switch( 3 ) {
        case [1,3,5]:
          assert true
          break
        default:
          assert false
      }

Parameters:
  `switchValue` - the switch value.

Returns:
  true if the caseValue is deemed to contain the switchValue

Since:
  1.0

See:
  Collection#contains.

### join

    public String join(String separator)

  Concatenates the `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(", ")

Parameters:
  `separator` - a String separator.

Returns:
  the joined String

Since:
  1.0

### leftShift

    public Collection leftShift(Object value)

  Overloads the left shift operator to provide an easy way to append objects to a Collection.

      def list = [1,2]
      list << 3
      assert list == [1,2,3]

Parameters:
  `value` - an Object to be added to the collection..

Returns:
  same collection, after the value was added to it.

Since:
  1.0

### max

    public Object max()

  Adds max() method to Collection objects.

      assert 5 == [2,3,1,5,4].max()

Returns:
  the maximum value

Since:
  1.0

See:
  GroovyCollections#max.

### max

    public Object max(Closure closure)

  Selects an item in the collection having the maximum value as determined by the supplied closure. 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

Parameters:
  `closure` - a 1 or 2 arg Closure used to determine the correct ordering.

Returns:
  the maximum value

Since:
  1.0

### max

    public Object max(Comparator comparator)

  Selects the maximum value found in the collection using the given comparator.

      assert "hello" == ["hello","hi","hey"].max( { a, b -> a.length() <=> b.length() } as Comparator )

Parameters:
  `comparator` - a Comparator.

Returns:
  the maximum value

Since:
  1.0

### min

    public Object min()

  Adds min() method to Collection objects.

      assert 2 == [4,2,5].min()

Returns:
  the minimum value

Since:
  1.0

See:
  GroovyCollections#min.

### min

    public Object min(Comparator comparator)

  Selects the minimum value found in the collection using the given comparator.

      assert "hi" == ["hello","hi","hey"].min( { a, b -> a.length() <=> b.length() } as Comparator )

Parameters:
  `comparator` - a Comparator.

Returns:
  the minimum value

Since:
  1.0

### min

    public Object min(Closure closure)

  Selects an item in the collection having the minimum value as determined by the supplied closure. 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

Parameters:
  `closure` - a 1 or 2 arg Closure used to determine the correct ordering.

Returns:
  the minimum value

Since:
  1.0

### multiply

    public List multiply(Number factor)

  Create a List composed of the elements of this list, repeated a certain number of times. Note that for non-primitive elements, multiple references to the same instance will be added.

      assert [1,2,3,1,2,3] == [1,2,3] * 2

Parameters:
  `factor` - the number of times to append.

Returns:
  the multiplied list

Since:
  1.0

### plus

    public Collection plus(Collection right)

  Create a Collection as a union of two collections. If the left collection is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.

      assert [1,2,3,4] == [1,2] + [3,4]

Parameters:
  `right` - the right Collection.

Returns:
  the merged Collection

Since:
  1.5.0

### plus

    public Collection plus(Object right)

  Create a collection as a union of a Collection and an Object. If the collection is a Set, then the returned collection will be a Set otherwise a List. This operation will always create a new object for the result, while the operands remain unchanged.

      assert [1,2,3] == [1,2] + 3

Parameters:
  `right` - an object to add/append.

Returns:
  the resulting Collection

Since:
  1.5.0

### removeAll

    public boolean removeAll(Object[] items)

  Removes all of this collection's elements that are also contained in the specified array. After this call returns, this collection will contain no elements in common with the specified array.

Parameters:

Returns:
  `true` if this collection changed as a result of the call

Since:
  1.7.2

See:
  Collection#removeAll(Collection).

### removeAll

    public boolean removeAll(Closure closure)

  Removes the elements in this collection that are matched according to the specified closure condition.

Parameters:
  `closure` - a closure condition.

Returns:
  `true` if this collection changed as a result of the call

Since:
  1.7.2

See:
  Iterator#remove().

### retainAll

    public boolean retainAll(Object[] items)

  Retains only the elements in this collection that are contained in the specified array. In other words, removes from this collection all of its elements that are not contained in the specified array.

Parameters:

Returns:
  `true` if this collection changed as a result of the call

Since:
  1.7.2

See:
  Collection#retainAll(Collection).

### retainAll

    public boolean retainAll(Closure closure)

  Retains only the elements in this collection that are matched according to the specified closure condition. In other words, removes from this collection all of its elements that don't match.

Parameters:
  `closure` - a closure condition.

Returns:
  `true` if this collection changed as a result of the call

Since:
  1.7.2

See:
  Iterator#remove().

### sort

    public List sort()

  Sorts the given collection into a sorted list. The collection items are assumed to be comparable.

      assert [1,2,3] == [3,1,2].sort()

Returns:
  the sorted collection as a List

Since:
  1.0

### sort

    public List sort(Comparator comparator)

  Sorts the Collection using the given comparator. The elements are sorted into a new list, and the existing collection is unchanged.

      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)

Parameters:
  `comparator` - a Comparator used for the comparison.

Returns:
  a newly created sorted List

Since:
  1.0

### sort

    public List sort(Closure closure)

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

      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { it.length() }

      assert ["hi","hey","hello"] == ["hello","hi","hey"].sort { a, b -> a.length() <=> b.length() }

Parameters:
  `closure` - a 1 or 2 arg Closure used to determine the correct ordering.

Returns:
  a newly created sorted List

Since:
  1.0

### split

    public Collection split(Closure closure)

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

      assert [[2,4],[1,3]] == [1,2,3,4].split { it % 2 == 0 }

Parameters:
  `closure` - a closure condition.

Returns:
  a List containing whose first item is the accepted values and whose second item is the rejected values

Since:
  1.6.0

### sum

    public Object sum()

  Sums the items in a collection. This is equivalent to invoking the "plus" method on all items in the collection.

      assert 1+2+3+4 == [1,2,3,4].sum()

Returns:
  The sum of all of the items

Since:
  1.0

### sum

    public Object sum(Object initialValue)

  Sums the items in a collection, adding the result to some initial value.

      assert 5+1+2+3+4 == [1,2,3,4].sum(5)

Parameters:
  `initialValue` - the items in the collection will be summed to this initial value.

Returns:
  The sum of all of the items.

Since:
  1.5.0

### sum

    public Object sum(Closure closure)

  Sums the result of apply a closure to each item of a collection. `coll.sum(closure)` is equivalent to: `coll.collect(closure).sum()`.

      assert 4+6+10+12 == [2,3,5,6].sum() { it * 2 }

Parameters:
  `closure` - a single parameter closure that returns a numeric value..

Returns:
  The sum of the values returned by applying the closure to each item of the collection.

Since:
  1.0

### sum

    public Object sum(Object initialValue, Closure closure)

  Sums the result of applying a closure to each item of a collection to some initial value. `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 }

Parameters:
  `closure` - a single parameter closure that returns a numeric value..
  `initialValue` - the closure results will be summed to this initial value.

Returns:
  The sum of the values returned by applying the closure to each item of the collection.

Since:
  1.5.0

### toList

    public List toList()

  Convert a Collection to a List. Always returns a new List even if the Collection is already a List.

  Example usage:

      def x = [1,2,3] as HashSet
      assert x.class == HashSet
      assert x.toList() instanceof List

Returns:
  a List

Since:
  1.0

### toListString

    public String toListString()

  Returns the string representation of the given list. The string displays the contents of the list, similar to a list literal, i.e. `[1, 2, a]`.

Returns:
  the string representation

Since:
  1.0

### toListString

    public String toListString(int maxSize)

  Returns the string representation of the given list. The string displays the contents of the list, similar to a list literal, i.e. `[1, 2, a]`.

Parameters:
  `maxSize` - stop after approximately this many characters and append '...'.

Returns:
  the string representation

Since:
  1.7.3

### unique

    public Collection unique()

  Modifies this collection to remove all duplicated items, using the default comparator.

      assert [1,3] == [1,3,3].unique()

Returns:
  the now modified collection

Since:
  1.0

### unique

    public Collection unique(Closure closure)

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

      assert [1,4] == [1,3,4,5].unique { it % 2 }

      assert [2,3,4] == [2,3,3,4].unique { a, b -> a <=> b }

Parameters:
  `closure` - a 1 or 2 arg Closure used to determine unique items.

Returns:
  self without any duplicates

Since:
  1.0

### unique

    public Collection unique(Comparator comparator)

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

  `

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

          class PersonComparator implements Comparator {
              public 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)
              }

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

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

          def list = [a, b, c, d]
          List list2 = list.unique(new PersonComparator())
          assert( list2 == list && list == [a, b, c] )

  `

Parameters:
  `comparator` - a Comparator.

Returns:
  self the now modified collection without duplicates

Since:
  1.0

Overview | Package | Class | Tree | Deprecated | Index | Help
| Groovy JDK