Created
January 8, 2016 18:40
-
-
Save jonatasemidio/538c0422a89115c7fa68 to your computer and use it in GitHub Desktop.
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', '=', '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