Created
January 8, 2016 18:50
-
-
Save jonatasemidio/489860da398a8d4cf09f to your computer and use it in GitHub Desktop.
retainAll method samples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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