Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
@colaru
Copy link
Author

colaru commented Jan 7, 2017

An example of closure where we illustrate how we can do in Groovy map/reduce on an array.

@chb0github
Copy link

chb0github commented Aug 10, 2017

what about filter? findAll ?

@bitsnaps
Copy link

bitsnaps commented Jul 25, 2019

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

chb0github commented Jul 25, 2019

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