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
...