Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@colaru
Last active October 19, 2021 19:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save colaru/294af9d9c889cbfa262a7f356258c47e to your computer and use it in GitHub Desktop.
Save colaru/294af9d9c889cbfa262a7f356258c47e to your computer and use it in GitHub Desktop.
// Groovy map-reduce example
// declare a closure
def half = { it ->
it / 2
}
// declare another closure
def sum = { result, i ->
result + i
}
// initialisation of an array of numbers
def numbers = [2, 0, 1, 7]
// map (named collect in Groogy)
def halfNumbers = numbers.collect(half)
assert halfNumbers == [1, 0, 0.5, 3.5]
// reduce (named inject in Groovy)
def total = numbers.inject(0, sum)
assert total == 10
@bitsnaps
Copy link

what about filter? findAll ?

@chb0github, What do you wanna do in this case?

  def total = numbers.findAll{it > 2}.grep(Number).inject(0, sum)
  assert total == 7

@chb0github
Copy link

I asked this question long ago when I was much less knowledgable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment