Last active
October 19, 2021 19:35
-
-
Save colaru/294af9d9c889cbfa262a7f356258c47e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
what about filter
? findAll
?
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
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
An example of closure where we illustrate how we can do in Groovy map/reduce on an array.