Saqib Ali
Saqib Ali

Reputation: 4448

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?

Upvotes: 0

Views: 485

Answers (3)

pacman
pacman

Reputation: 837

Very similar example:

  val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")

  s.groupBy(identity).mapValues(_.size)

And result is

Map(banana -> 1, oranges -> 3, apple -> 3)

And for certain item:

s.groupBy(identity).mapValues(_.size)("apple")

Upvotes: 2

Brian
Brian

Reputation: 20295

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

Upvotes: 5

dk14
dk14

Reputation: 22374

scala> list.count(Set("this", "that").contains)
res12: Int = 3
  • it's shorter
  • it's one-pass

If you need to count words in several different places using the same big list:

val m = list.groupBy(identity).mapValues(_.size).withDefaultValue(0)

will give you a handy Map with all counts, so you could do

scala> m("this") + m("that")
res11: Int = 3

Upvotes: 3

Related Questions