Created
May 16, 2012 15:27
-
-
Save cdeszaq/2711283 to your computer and use it in GitHub Desktop.
Using inject with a map to count occurrences of strings
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
import groovy.json.JsonOutput | |
// File is just a list of words, one per line. | |
def counts = new File("types.txt").readLines().inject([:]) {Map obj, String val -> | |
// If we hit an empty line, do nothing and just return the map as-is | |
if (val) { | |
if (!obj[val]) { | |
// The key didn't exist, so put it into the map | |
obj[val] = 1 | |
} else { | |
// Increment the counter | |
obj[val]++ | |
} | |
} | |
obj // Return the map when we are done | |
} | |
// Print the counts | |
println JsonOutput.prettyPrint(JsonOutput.toJson(counts)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice example of how to use inject. I found it can be combined with Map default values for even more Groovy goodness: