I’ve been working with Groovy for some time now and I think it’s one of the best languages for the JVM.

To show my love for this language I dedicate this weekend to showcase some of the enhancements Groovy has made to working with Lists, Maps and Collections. Some small tidbits – just for fun.

In this 6th installment of the Groovy Weekend Collections Showcase Reel…


removeAll

removeAll() is a method on Collection which normally gets passed an array of objects to remove. There’s also a variant which accepts a closure – which specifies the condition if an element should be removed.

 
class Animal {
    String name
    int age
    String toString() { properties }
}

def animals = []
animals << new Animal(name: "Buttercup", age: 2)
animals << new Animal(name: "Carmella", age: 5)
animals << new Animal(name: "Cinnamon", age: 2)

// remove all animals younger than 3
animals.removeAll { it.age < 3 }
assert animals.size() == 1
assert animals.first().name == "Carmella"

Next to removing there’s also a retainAll. Check out Groovy’s GDK documentation.

Advertisements