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,890 questions

51,817 answers

573 users

How to group words by first letter in Scala

1 Answer

0 votes
object GroupWordsApp {

  /**
    * Groups words by their first letter.
    *
    * @param words A sequence of words to group
    * @return A Map where each key is a first letter and each value is a list of words
    */
  def groupByFirstLetter(words: Seq[String]): Map[Char, Seq[String]] = {
    // groupBy creates a Map[Char, Seq[String]]
    // _.head extracts the first character of each word
    words.groupBy(_.head)
  }

  def main(args: Array[String]): Unit = {

    // List of words to group
    val words = Seq(
      "Python", "JavaScript", "C", "Java", "C#", "PHP",
      "C++", "Pascal", "SQL", "Rust"
    )

    val grouped = groupByFirstLetter(words)

    // Print each group 
    for ((letter, group) <- grouped) {
      println(s"$letter: [${group.mkString(", ")}]")
    }

    // Print the entire map
    println(grouped)
  }
}




/*
run:

J: [JavaScript, Java]
P: [Python, PHP, Pascal]
C: [C, C#, C++]
R: [Rust]
S: [SQL]
HashMap(J -> List(JavaScript, Java), P -> List(Python, PHP, Pascal), C -> List(C, C#, C++), R -> List(Rust), S -> List(SQL))

*/


 



answered Jan 17 by avibootz
...