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
Written by lukas
Related protips
3 Responses
Add your response
Add your response
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#