Saqib Ali Saqib Ali - 1 year ago 91
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download