计算任何项目在Scala列表中显示的次数

Saq*_*Ali 0 scala

我有以下列表:

val list = List("this", "this", "that", "there", "here", "their", "where")
Run Code Online (Sandbox Code Playgroud)

我想计算"这个"或"那个"出现多少次.我可以这样做:

 list.count(_ == "this") + list.count(_ == "that")
Run Code Online (Sandbox Code Playgroud)

有最简洁的方法吗?

Bri*_*ian 5

您一次可以count多次出现.无需拨打count两次电话.

scala> list.count(x => x == "this" || x == "that")
res4: Int = 3
Run Code Online (Sandbox Code Playgroud)