
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
In this tutorial, we’ll learn how to count all occurrences of a given char in a String in Scala.
For the purpose of the tutorial, we’re going to focus on the methods that are Scala-specific and available in the standard library.
The most idiomatic way to perform the task is to use the count() method. The count() method accepts a function returning Boolean and automatically counts all elements for which the given function is true:
private def countWithCount(string: String, char: Char): Int = string.count(_ == char)
We can also use filter() combined with size to achieve our goal:
private def countWithFilter(string: String, char: Char): Int = string.filter(_ == char).size
Another way we can count the occurrences of a char in a String is to compose three different methods groupBy(), mapValues(), and reduce():
def countWithGroupBy(string: String, char: Char): Int =
string.groupBy(identity).mapValues(_.map(_ => 1).reduce(_+_))(char)
The above pattern was used so often that, in Scala 2.13, a new method – mapGroupReduce() – was introduced to simplify its usage.
Although Scala offers some simple out-of-the-box solutions to solve our problem, it’s also possible to use tail-recursion for that:
def countRecursive(string: String, char: Char): Int = {
@tailrec
def countRec(string: String, char: Char, count: Int): Int = {
if(string.isEmpty) {
count
} else {
val newCount = if(string.head == char) count + 1 else count
countRec(string.tail, char, newCount)
}
}
countRecursive(string, char)
}
In this tutorial, we’ve learned different ways to count all occurrences of a char inside a String in Scala.
Because of the interoperability between Java and Scala, we can also use any of the methods described in our related article for Java.