How to count the occurrences of each letter in char array with Scala

1 Answer

0 votes
object LetterCounter {
  def countLetters(chars: Array[Char]): Map[Char, Int] = {
    chars.groupBy(identity).view.mapValues(_.length).toMap
  }

  def main(args: Array[String]): Unit = {
    val charArray = Array('s', 'c', 's', 'c', 'd', 'c', 'e', 'f', 'e', 's')
    val letterCounts = countLetters(charArray)
    
    println(letterCounts)

    letterCounts.foreach { case (key, value) =>
      println(s"Letter:$key $value times")
    }
  }
}



/*
run:

HashMap(e -> 2, s -> 3, f -> 1, c -> 3, d -> 1)
Letter:e 2 times
Letter:s 3 times
Letter:f 1 times
Letter:c 3 times
Letter:d 1 times
 
*/

 



answered Mar 3, 2025 by avibootz

Related questions

...