Scala how can I count the number of occurrences in a list

val list = List(1,2,4,2,4,7,3,2,4)

我想要像这样实现它: list.count(2) (返回3)。


A somewhat cleaner version of one of the other answers is:

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

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

giving a Map with a count for each item in the original sequence:

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

The question asks how to find the count of a specific item. With this approach, the solution would require mapping the desired element to its count value as follows:

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

斯卡拉集合确实有countlist.count(_ == 2)


I had the same problem as Sharath Prabhal, and I got another (to me clearer) solution :

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(l => l).map(t => (t._1, t._2.length))

With as result :

Map(banana -> 1, oranges -> 3, apple -> 3)
链接地址: http://www.djcxy.com/p/86188.html

上一篇: Scala中方法和函数的区别

下一篇: 斯卡拉我如何计算列表中发生的次数