Groovy Weekend – Collections: Grouping And Summing Items

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.

This is the 7th and last installment of the Groovy Weekend Collections Showcase Reel – at least for this weekend 🙂 which we’ll conclude with grouping, collecting and summing.


sum

sum() is a method on Iterable which ehm,…sums up all items – using the plus() method under the hood.

class Animal {
 String name
 BigDecimal price
 String farmer
 String toString() { name }
}

def animals = []
animals << new Animal(name: "Buttercup", price: 2, farmer: "john")
animals << new Animal(name: "Carmella", price: 5, farmer: "dick")
animals << new Animal(name: "Cinnamon", price: 2, farmer: "dick")

// gather the total price of all animals
assert 9 == animals.sum { it.price }
assert 9 == animals.price.sum()

Putting it all together

// grouping: animals by farmer
def animalsByFarmer = animals.groupBy { it.farmer }
assert "[john:[Buttercup], dick:[Carmella, Cinnamon]]" 
               == animalsByFarmer.toString()

// grouping and summing: total price per farmer
def totalPriceByFarmer = animals
                            .groupBy { it.farmer }
                            .collectEntries { k, v -> 
                                [k, v.price.sum()]
                            }
assert ['john':2, 'dick':7] == totalPriceByFarmer

That’s it – the last edition this weekend! Check out more of Groovy’s methods on Iterable and Collection in the GDK documentation.

No animals were hurt while making these examples. For now, I’ll hope you will enjoy Groovy as much as I do. 🙂

Groovy Weekend – Collections: Injecting or Map Reduce

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 7th installment of the Groovy Weekend Collections Showcase Reel…


inject

inject() is a method on Collection which iterates all elements, passing 1st item to specified closure, injecting results back into closure with 2nd item, etc

First an abstract example:

assert 1 * 2 * 3 * 4 == 
    [1, 2, 3, 4].inject { current, val -> current * val }

And – as you would expect by now – some animals:

class Animal {
    String name
    BigDecimal price
    String farmer
}

def animals = []
animals << new Animal(name: "Buttercup", price: 2, farmer: "john")
animals << new Animal(name: "Carmella", price: 5, farmer: "dick")
animals << new Animal(name: "Cinnamon", price: 2, farmer: "dick")

// gather the total price of all animals, passing initial price of 0
assert 9 == animals.inject(0) { totalPrice, animal -> 
    totalPrice + animal.price 
}
// or...
assert 9 == animals.price.inject(0) { totalPrice, price -> 
    totalPrice + price
}

There are some variants of inject, one which takes an initial value and one which takes the head of the collection as initial value. Check out Groovy’s GDK documentation.

Groovy Weekend – Collections: Removing Matching Items

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.

Groovy Weekend – Collections: Collecting or Mapping Entries

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 5th installment of the Groovy Weekend Collections Showcase Reel…


collectEntries

collectEntries() is a method on Iterable to iterate on its elements, transforming the values – specified by a closure – and returning them in a new Map.

 
class Farmer { String name }
class Animal {
    String name
    Farmer farmer
}

def john = new Farmer(name: "John")
def dick = new Farmer(name: "Dick")

def animals = []
animals << new Animal(name: "Buttercup", farmer: john)
animals << new Animal(name: "Carmella", farmer: dick)
animals << new Animal(name: "Cinnamon", farmer: dick)

// collect farmer name by animal name
def results = animals.collectEntries { animal -> 
 [animal.name, animal.farmer.name]
}
assert results == ['Buttercup':'John', 
 'Carmella':'Dick', 
 'Cinnamon':'Dick']

 


There are some overloaded variants of collectEntries. Check out Groovy’s GDK documentation.

Groovy Weekend – Collections: Sorting and Grouping Items

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 4th installment of the Groovy Weekend Collections Showcase Reel…


groupBy

groupBy() is a method on Iterable to group items according to a mapping closure. You’ll get a LinkedHashMap grouped by the key returned by the closure.

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

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

// single closure
Map animalsByCountry = animals.groupBy { it.country }
assert animalsByCountry["NL"].size() == 2 // Buttercup and Carmella
assert animalsByCountry.BE.size() == 1 // Cinnamon

There’s also an option to pass multiple closures.

 
Map animalsByCountryAndAge = 
        animals.groupBy( [{ it.country }, { it.age }] )
    
assert animalsByCountryAndAge.toString() == 
        "[NL:[2:[Buttercup], 5:[Carmella]], BE:[2:[Cinnamon]]]"

There are some overloaded variants of groupBy. Check out Groovy’s GDK documentation.

Groovy Weekend – Collections: Finding Items In a Collection

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 3rd installment of the Groovy Weekend Collections Showcase Reel…


find and findAll

find() and findAll() are methods on Collection to find items which match the criteria of a specified closure according to the Groovy Truth.

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

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

// find first matching animal 
Animal foundAnimal = animals.find { it.age == 2 }
assert foundAnimal.name == "Buttercup"

// find all matching animals
List foundAnimals = animals.findAll { it.name.startsWith "C" } 
assert foundAnimals.toString() == "[Carmella, Cinnamon]"

I use these methods a lot! There are some overloaded variants of find and findAll. Check out Groovy’s GDK documentation.

Groovy Weekend – Collections: Collecting and Transforming Items

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 2nd installment of the Groovy Weekend Collections Showcase Reel…


collect

collect() is a method on Collection to iterate on its elements, transforming the values – specified by a closure – and returning them in a new List.

 
class Animal {
    String name
    int age
}

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

// collect on List
def names = animals.collect { it.name }
assert names == ["Buttercup", "Carmella", "Cinnamon"] 
// names is java.util.ArrayList

You can also collect as a different type e.g. a Set, keeping only unique values, while passing this Set as a 1st parameter, and the closure 2nd.

 
assert animals.collect(new HashSet()) { it.age }.toString() == "[2, 5]"

There are many overloaded variants of collect. Check out Groovy’s GDK documentation.

Groovy Weekend – Collections: Splitting or Collating a List

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 every few hours.

I’ll call it the Groovy Weekend Collections Showcase Reel!…ahem. In this first installment we’ll start with…


collate

collate() is a method on any Iterable to split or partition its elements into a sub-list of a certain size.

 
def names = ["Lassy", 
             "Buttercup", 
             "Carmella", 
             "Moo-moo", 
             "Cinnamon"]

// collate into batches of 3
def collated = names.collate 3
assert collated ==  
    [['Lassy', 'Buttercup', 'Carmella'], 
     ['Moo-moo', 'Cinnamon']]

You can even pass a 2nd parameter as the number of elements to step through for each sub-list.

collated = names.collate 3, 1
assert collated == [['Lassy', 'Buttercup', 'Carmella'], 
                    ['Buttercup', 'Carmella', 'Moo-moo'], 
                    ['Carmella', 'Moo-moo', 'Cinnamon'], 
                    ['Moo-moo', 'Cinnamon'], 
                    ['Cinnamon']]

There are many overloaded variants of colate. Check out Groovy’s GDK documentation.

How to mock configuration in a Grails unit- or integration test?

Sometimes you may need to mock Grails (application) configuration in an unit or integration test.

E.g. you want to test code which normally would access the property jmxEnabled from the following configuration block:

In Grails 2 in Config.groovy

someService {
  jmxEnabled = true
}

or Grails 3 in application.yml

someService:
  jmxEnabled: true

Here’s are the most simple options for a Grails 2.4.x or Grails 3.0.x Spock unit- or integration test.

Unit test

In your unit test you have an implicit config reference you can use. Either in a specific test or in a setup() initialize it with a value you want to test with.

@TestFor(MyService)
class MyServiceSpec extends Specification {

  def setup() {
    config.someService.jmxEnabled = false
  }

This is actually the getConfig() method in the GrailsUnitTestMixin class which Grails automatically “mixes” into your unit test class.

Integration test

In your integration test, inject grailsApplication as a bean and access the configuration through its config property – just as you would in the actual production code.

class MyServiceIntegrationSpec extends Specification {

  def grailsApplication
  ...

  def setup() {
    grailsApplication.config.someService.jmxEnabled = false
  }

Written for Grails 2.4+ and Grails 3.0.x.