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

51,766 answers

573 users

How to convert a sequence of strings and group all the anagrams into subsequences in Scala

1 Answer

0 votes
object AnagramGrouper {

  // Groups an array of strings into subarrays of anagrams
  def groupAnagrams(words: Seq[String]): Seq[Seq[String]] = {
    // Validate input
    if (words.exists(_.isEmpty)) throw new IllegalArgumentException("All elements must be non-empty strings.")

    // Group words by their sorted character key
    val grouped = words.groupBy(word => word.sorted)

    // Return grouped anagrams as a sequence of sequences
    grouped.values.toSeq
  }

  def main(args: Array[String]): Unit = {
    val arr = Seq("eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro")

    try {
      val result = groupAnagrams(arr)
      println("Grouped anagrams:")
      result.foreach(group => println(group.mkString("[", ", ", "]")))
    } catch {
      case e: Exception => println(s"Error: ${e.getMessage}")
    }
  }
}




/*
run:

Grouped anagrams:
[bat]
[nat, tan]
[eat, tea, ate]
[rop, orp, pro]

*/

 



answered Nov 15, 2025 by avibootz
...