Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Groovy Practice Exercises with Solutions

Twelve Groovy exercises from collections and closures to metaprogramming, builders and Spock, each with a hint, a solution and a runnable Java check of the logic.

Reading about Groovy is not the same as writing it. These exercises cover the whole course, from everyday collection work to metaprogramming and tests. Try each one on paper or in a Groovy console on your own machine before opening the solution. The solutions are idiomatic Groovy; the Java programs at the end let you check the logic of several of them on this site.

Groovy cannot run on this site, so the Groovy code is read-only. Run the exercises locally with groovy script.groovy or in the Groovy web console. The outputs given in comments are the values you should see.

Warm-up: collections and closures

1. Word frequencies

Given a sentence, return a map of lowercase word to count, ignoring punctuation, sorted by count descending, then alphabetically.

Hint: split, countBy, sort with a two-key comparator.

GROOVY
def freq(String text) {
  text.toLowerCase().findAll(/[a-z']+/)
      .countBy { it }
      .sort { a, b -> b.value <=> a.value ?: a.key <=> b.key }
}

println freq("The cat and the hat. The end!")
// [the:3, and:1, cat:1, end:1, hat:1]

2. Group anagrams

Group a list of words so that words with the same letters are together.

GROOVY
def anagrams(List<String> words) {
  words.groupBy { it.toList().sort().join() }.values().toList()
}

println anagrams(["listen", "silent", "enlist", "google", "gogole", "cat"])
// [[listen, silent, enlist], [google, gogole], [cat]]

3. Compose and curry

Write compose(f, g) returning a closure that applies g and then f. Use curry to make add5 from a two-argument add.

GROOVY
def compose = { f, g -> return { x -> f(g(x)) } }
def add = { a, b -> a + b }
def add5 = add.curry(5)
def timesTwo = { it * 2 }

println compose(add5, timesTwo)(10)   // 25
println((timesTwo >> add5)(10))       // 25  (>> composes left to right)

Classes and traits

4. Immutable value with validation

Create an immutable Temperature with a Celsius value that rejects values below -273.15 and offers toFahrenheit().

GROOVY
import groovy.transform.*

@ToString(includeNames = true)
@EqualsAndHashCode
final class Temperature {
  final BigDecimal celsius

  Temperature(BigDecimal celsius) {
    if (celsius < -273.15) throw new IllegalArgumentException("below absolute zero")
    this.celsius = celsius
  }

  BigDecimal toFahrenheit() { celsius * 9 / 5 + 32 }
}

println new Temperature(100).toFahrenheit()   // 212

A class with only final fields and no setters is immutable. @Immutable generates the same shape, but it builds its own constructors, which is why the explicit validation above is written by hand.

5. A trait for timestamps

A trait Auditable adds createdAt and a method age() returning the seconds since creation. Apply it to two unrelated classes.

GROOVY
trait Auditable {
  long createdAt = System.currentTimeMillis()
  long age() { (System.currentTimeMillis() - createdAt).intdiv(1000) }
}

class Invoice implements Auditable { String number }
class User implements Auditable { String name }

assert new Invoice(number: "A1").age() >= 0
assert new User(name: "Ada").age() >= 0

Metaprogramming and DSLs

6. A humanize method on Integer

Add Integer.metaClass.humanize that turns 1500 into "1.5K" and 2_300_000 into "2.3M", but do it with a category so it does not leak.

GROOVY
class NumberCategory {
  static String humanize(Integer self) {
    if (self >= 1_000_000) return String.format("%.1fM", self / 1_000_000)
    if (self >= 1_000)     return String.format("%.1fK", self / 1_000)
    return self.toString()
  }
}

use(NumberCategory) {
  println 1500.humanize()        // 1.5K
  println 2_300_000.humanize()   // 2.3M
  println 42.humanize()          // 42
}

7. Dynamic finders

Make a People class where findByAge(30) and findByCity("Oslo") work without defining either method.

GROOVY
class People {
  List rows = []

  def methodMissing(String name, args) {
    def m = name =~ /^findBy(\w+)$/
    if (!m) throw new MissingMethodException(name, People, args)
    String field = m[0][1].uncapitalize()
    rows.findAll { it[field] == args[0] }
  }
}

8. A tiny HTML DSL

Write html { body { h1 "Hi"; p "text" } } producing <html><body><h1>Hi</h1><p>text</p></body></html>, without MarkupBuilder.

GROOVY
class Html {
  StringBuilder out = new StringBuilder()

  def methodMissing(String tag, args) {
    out << "<$tag>"
    def body = args[0]
    if (body instanceof Closure) {
      body.delegate = this
      body.resolveStrategy = Closure.DELEGATE_FIRST
      body()
    } else {
      out << body
    }
    out << "</$tag>"
  }
}

static String html(Closure c) {
  def h = new Html()
  h.html(c)
  h.out.toString()
}

Data and testing

9. Parse and total

Given the XML <order><item price="2.5" qty="4"/><item price="10" qty="1"/></order>, compute the total price with XmlSlurper.

GROOVY
def order = new XmlSlurper().parseText('<order><item price="2.5" qty="4"/><item price="10" qty="1"/></order>')
def total = order.item.collect { [email protected]() * [email protected]() }.sum()
println total    // 20.0

10. A data-driven Spock test

Write a Spock specification for a fizzbuzz(n) function with a where: table covering 1, 3, 5, 15 and 7.

GROOVY
class FizzBuzzSpec extends Specification {
  def "fizzbuzz of #n is #expected"() {
    expect:
    fizzbuzz(n) == expected

    where:
    n  || expected
    1  || "1"
    3  || "Fizz"
    5  || "Buzz"
    15 || "FizzBuzz"
    7  || "7"
  }
}

11. Mock the mailer

Test that OrderService.place(order) sends exactly one confirmation email and never sends anything when the order is empty.

GROOVY
def "places order and mails once"() {
  given:
  def mailer = Mock(Mailer)
  def service = new OrderService(mailer)

  when:
  service.place(new Order(items: ["pen"]))

  then:
  1 * mailer.send(_, _)
}

def "empty order sends nothing"() {
  given:
  def mailer = Mock(Mailer)

  when:
  new OrderService(mailer).place(new Order(items: []))

  then:
  0 * mailer.send(*_)
  thrown(IllegalArgumentException)
}

12. Grape script

Write a script that grabs Commons Lang and prints StringUtils.abbreviate("a long sentence about Groovy", 15).

GROOVY
@Grab('org.apache.commons:commons-lang3:3.14.0')
import org.apache.commons.lang3.StringUtils

println StringUtils.abbreviate("a long sentence about Groovy", 15)   // a long sente...

How to practice effectively

  1. Solve it first without looking, then compare. Note what the solution does with fewer lines.
  2. Rewrite each solution in a second way (for example a loop and then inject).
  3. Add a Spock test for every function you write.
  4. Run your scripts with -e for one-liners and groovysh for experiments.
  5. Re-read the lessons on metaclass and dynamic dispatch and closure delegates whenever a DSL surprises you.

Try it: check exercises 1 and 2 (stand-in)

The same algorithms in Java. The output equals the values in the Groovy comments.

Java Stand-in: word frequency and anagram groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: check exercises 3 and 7 (stand-in)

Function composition with currying, and a finder that parses a method name.

Java Stand-in: compose, curry and findBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Groovy method groups items by a key and returns a map of key to list?

    groupBy returns a map whose values are lists, while countBy returns counts.
  2. 2. Why prefer a category over adding a method through metaClass for a one-off helper?

    A category's methods disappear after the use block, which keeps global behavior unchanged.
  3. 3. In Spock, which block checks that a mock was never called?

    An interaction with count 0 asserts that no matching call happened.
  4. 4. What does timesTwo >> add5 mean for closures?

    The >> operator composes closures left to right.

Summary

  • The exercises cover collections, closures, traits, categories, methodMissing, delegates, XML parsing, Spock tables, mocks and Grape.
  • Solve first, compare second, then rewrite in another style and add a test.
  • Revisit the lessons on metaprogramming and DSLs when you meet a surprising behavior.
  • You now have the vocabulary to read Gradle files, Spock tests and Groovy libraries with confidence.

Next: back to the Groovy tutorial overview