Last active
November 15, 2024 12:31
-
-
Save Graham42/f84265059d3b3f8b5ff372d7d633fcb6 to your computer and use it in GitHub Desktop.
Groovy example for map, filter, reduce
This file contains 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
// In Groovy | |
// collect = "map" | |
// inject = "reduce" | |
// | |
// See http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html for docs | |
//////////////////////////////////////////////////////////////////////////////// | |
// Arrays | |
def myNumbers = [3, 5, 1] | |
// Map example | |
def biggerNumbers = myNumbers.collect({ x -> | |
x + 4 | |
}) | |
assert biggerNumbers == [7, 9 , 5] | |
// Filter example | |
assert [1, 2, 3].findAll { it > 1 } == [2, 3] | |
// Reduce example | |
def total = myNumbers.inject(0, { result, x -> | |
result + x | |
}) | |
assert total == 9 | |
// combined example | |
def otherTotal = myNumbers.collect({ x -> | |
x + 1 | |
}).inject(0, { result, x -> | |
result + x | |
}) | |
assert otherTotal == 12 | |
//////////////////////////////////////////////////////////////////////////////// | |
// Dictionaries | |
def pets = [ | |
dogs: 2, | |
cats: 1, | |
parrots: 0, | |
] | |
// Map example | |
def petKinds = pets.collect({ kind, count -> | |
kind | |
}) | |
assert petKinds == ["dogs", "cats", "parrots"] | |
// Filter example | |
def petsThatExist = pets.findAll({ kind, count -> | |
count > 0 | |
}).collect({ kind, count -> | |
kind | |
}) | |
assert petsThatExist == ["dogs", "cats"] | |
// Reduce example | |
def totalPets = pets.inject(0, {result, kind, count -> | |
result + count | |
}) | |
assert totalPets == 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment