Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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

I want to implement it like this: list.count(2) (returns 3).

like image 958
Gatspy Avatar asked Jul 12 '12 09:07

Gatspy


People also ask

How do you count instances in a list?

Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.

How do you count the number of occurrences of a character in a string in Scala?

The count() method in Scala is used to count the occurrence of characters in the string. The function will return the count of a specific character in the string.

What is sequence in Scala?

Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes.


2 Answers

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") 
like image 53
mattsilver Avatar answered Sep 23 '22 18:09

mattsilver


scala collections do have count: list.count(_ == 2)

like image 44
xiefei Avatar answered Sep 23 '22 18:09

xiefei