Skip to content

Instantly share code, notes, and snippets.

@Graham42
Last active May 25, 2022 16:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Graham42/f84265059d3b3f8b5ff372d7d633fcb6 to your computer and use it in GitHub Desktop.
Save Graham42/f84265059d3b3f8b5ff372d7d633fcb6 to your computer and use it in GitHub Desktop.
Groovy example for map, filter, reduce
// 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