Skip to content

Instantly share code, notes, and snippets.

@jonatasemidio
Created January 8, 2016 18:50
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/489860da398a8d4cf09f to your computer and use it in GitHub Desktop.
Save jonatasemidio/489860da398a8d4cf09f to your computer and use it in GitHub Desktop.
retainAll method samples
// 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', 42, 'gr8!', 5.2, new Date()]
// Groovy adds retainAll method
// to remove items from collection
// that do not apply to the condition we
// define in the closure and keep those
// items that do apply to the condition.
list.retainAll { it instanceof String }
// All values that are not a String
// object are removed.
// Remember the collection we use the
// retainAll method on is changed.
assert list == ['Groovy', 'gr8!']
def values = ['Hello', 'world', 'from', 'Groovy']
// Groovy adds retainAll(Object[])
// to keep multiple elements
// in a collection and remove all
// the other elements.
values.retainAll(['world', 'Hello'] as Object[])
assert values.join(' ') == 'Hello world'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment