I am new to Scala. Kindly help me with the expected output
val list =List(1,123,2,3,123,1,2)
val result = aList.map(x => aList.count(_==x)))
println(result.distinct)
Expected Output: Number of occurrence of 1 is 2 Number of occurrence of 2 is 2 Number of occurrence of 123 is 2 Number of occurrence of 3 is 1
groupBy
works well for this. It returns a Map
of elements grouped by a discriminator function which in the case is the element itself also known as identity
scala.collection.immutable.Map[Int,List[Int]] = HashMap(1 -> List(1, 1), 2 -> List(2, 2), 3 -> List(3), 123 -> List(123, 123))
Which we can work from.
Then map each key/value pair to a key and the size
of the values List
which gives what you are looking for.
list.groupBy(identity).map({case(k,v) => (k, v.size)})
scala.collection.immutable.Map[Int,Int] = HashMap(1 -> 2, 2 -> 2, 3 -> 1, 123 -> 2)
With Scala 2.13 we can use groupMapReduce
as LuisMiguelMejíaSuárez notes.
list.groupMapReduce(identity)(_ => 1)(_ + _)
Similar to the approach above, the first parameter is given the identity
function to group the values, the second parameter maps each value to 1
, and the third is given a function _ + _
to add them together.
This gives a similar answer as the original approach:
scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 2, 3 -> 1, 123 -> 2)