Skip to content

Instantly share code, notes, and snippets.

@cdeszaq
Created May 16, 2012 15:27
Show Gist options
  • Save cdeszaq/2711283 to your computer and use it in GitHub Desktop.
Save cdeszaq/2711283 to your computer and use it in GitHub Desktop.
Using inject with a map to count occurrences of strings
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))
@mrdanparker
Copy link

Nice example of how to use inject. I found it can be combined with Map default values for even more Groovy goodness:


    import groovy.json.JsonOutput

    // File is just a list of words, one per line. 

    def counts = new File("/tmp/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) {
            obj.get(val, 0)
            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