Last Updated: August 07, 2022
·
12.02K
· 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
    }
   counts
}

Returns Map form word to number of occurrences

3 Responses
Add your response

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 ·

@naderghanbari

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 ·