Last Updated: February 25, 2016
· lukasz-madon

Count number of words in a string (Scala)

This is improved snippet from Programming in Scala

def countWords(text: String) = {
    val counts = mutable.Map.empty[String, Int].withDefaultValue(0)
    for (rawWord <- text.split("[ ,!.]+")) {
         val word = rawWord.toLowerCase
            counts(word) += 1

Returns Map form word to number of occurrences

4 Responses
Add your response


Another implementation, perhaps more idiomatic Scala:

def countWords(text: String) = text.split("[ ,!.]+").map(_.toLowerCase).groupBy(identity).mapValues(_.size)
over 1 year ago ·

It is more idiomatic, but it's nlog(n)

over 1 year ago ·

why it's not nlog(n) and why the first one is?

over 1 year ago ·


First one is O(n) with O(n) memory. You iterate the collection once and store words in Map.

Second one is O(nlgn), because you sort the collection.

over 1 year ago ·