Providing a method on Seqs to count instances of each unique item?

Hi,

I’ve been using Scala for a bit over a year now, and I often find myself writing:

seq.groupBy(x => x).view.mapValues(_.length)

Is this the best way to count the number of each item in a Seq? If not, please let me know the better way. However, if this is indeed the best, it would be a kindness to include a method on Seq that computes this for users in one method call, perhaps seq.itemCounts().

Cheers,
Julian

Honestly, I suspect it’s too specialized to be likely to show up on Seq proper. (I can’t recall ever needing such a function myself.)

But I’d suggest adding it yourself: it’s not hard to make a class (or at worst a tiny library) with something like:

implicit class RichSeq[T](seq: Seq[T]) {
  def itemCounts: Map[T, Int] = seq.groupBy(x => x).view.mapValues(_.length)
}

It is a smallish Seq, toSet.length will be faster than most everything.

Am I missing something, or can you just use

seq.map(_.length)

Thanks, I suppose I can do this. I run into this problem a lot on various research projects - suppose you are running a simulation, and the simulation returns an outcome, and you want to count how many times each outcome occurred, etc. It is probably less useful for enterprise development. I will make use of this implicit, thanks!

That sounds how long each individual item is. What @julianzucker is looking for is the number of copies of each distinct item there are…

1 Like