Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to count the occurrences of each word in a string with Scala

1 Answer

0 votes
object WordCount extends App {
  val str = "Scala is a strong statically typed high-level general-purpose " + 
            "programming language. Scala supports both object-oriented " + 
            "programming and functional programming."

  // Split the str into words, convert to lowercase, and filter out empty strings
  val words = str.toLowerCase.split("\\W+").filter(_.nonEmpty)

  // Count the occurrences of each word
  val wordCount = words.groupBy(identity).view.mapValues(_.size).toMap

  wordCount.foreach { case (word, count) => println(s"$word: $count") }
}



/*
run:

is: 1
programming: 3
oriented: 1
a: 1
strong: 1
purpose: 1
supports: 1
scala: 2
both: 1
functional: 1
level: 1
statically: 1
typed: 1
object: 1
general: 1
language: 1
and: 1
high: 1
 
*/

 



answered Mar 2, 2025 by avibootz
...