Skip to content

Instantly share code, notes, and snippets.

@jonatasemidio
Created January 8, 2016 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonatasemidio/538c0422a89115c7fa68 to your computer and use it in GitHub Desktop.
Save jonatasemidio/538c0422a89115c7fa68 to your computer and use it in GitHub Desktop.
// Font: http://mrhaki.blogspot.fr/2015/09/groovy-goodness-removing-elements-from.html
// Thanks to Hubert Klein Ikkink (https://github.com/mrhaki)
def list = ['Groovy', '=', 'gr8!']
// Groovy adds removeAll method
// to remove items from collection
// that apply to the condition we
// define in the closure.
list.removeAll { it.toLowerCase().startsWith('g') }
// All values starting with a G or g
// are now removed.
// Remember the collection we use the
// removeAll method on is changed.
assert list == ['=']
// Java 8 adds removeIf method with
// a predicate. In Groovy we can implement
// the predicate as closure.
list.removeIf { it instanceof String }
assert list.size() == 0
def values = ['Hello', 'world']
// Groovy adds removeAll(Object[])
// to remove multiple elements
// from a collection.
values.removeAll(['world', 'Hello'] as Object[])
assert values.empty
def items = [1, 2, 3]
// remove method is overloaded
// for Object and index value.
// Because Groovy wraps int to
// Integer object, the method call
// is ambiguous for Integer collections.
items.remove(1)
// We want to remove object
// Integer(1) from the list,
// but item with index 1 is removed.
assert items == [1, 3]
// Groovy adds removeElement
// as alias for remove(Object).
items.removeElement(1)
assert items == [3]
// When the collection is a List
// we can use the removeAt method
// to remove based on index value.
items.removeAt(0)
assert !items
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment