Saqib Ali Saqib Ali - 3 months ago 7
Scala Question

Counting how many times any of the items appear in a Scala List

I have the following list:

val list = List("this", "this", "that", "there", "here", "their", "where")


I want to count how many times "this" OR "that" appears. I can do something like:

list.count(_ == "this") + list.count(_ == "that")


Is there most concise way of doing this?

Answer

You can count more than one occurrence at a time. No need to call count twice.

scala> list.count(x => x == "this" || x == "that")
res4: Int = 3
Comments