1

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

Brian
  • 20,195
  • 6
  • 34
  • 55
smp97
  • 63
  • 6

1 Answers1

2

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)

Brian
  • 20,195
  • 6
  • 34
  • 55
  • Thanks a lot for the help. – smp97 May 13 '20 at 17:08
  • 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 – smp97 May 13 '20 at 17:09
  • 1
    @SoumyaPillai that is a different question. You need to iterate the map and print the results, it shouldn't be that hard, think about how would you print each entry. - Brian, it may be good to tell that in **2.13** you can do the same with `groupMapReduce`. – Luis Miguel Mejía Suárez May 13 '20 at 17:27
  • 1
    @LuisMiguelMejíaSuárez Thanks for that. I've seen that before but have not kept up with **2.13** much. Here's what I came up with: `list.groupMapReduce(identity)(_ => 1)(_ + _)` – Brian May 13 '20 at 17:52
  • 1
    @Brian , @LuisMiguelMejíaSuárez Thanks for your help. I got the expected results. ```list.groupBy(identity).map({case(k,v)=> (k,v.size)}).foreach(x => println("Number of occurances of " + x._1 + " is : " + x._2)) ``` ```list.groupMapReduce(identity)(_ => 1)(_ + _).foreach(x => println("Number of occurancces of " + x._1 + " is :" + x._2)) ``` – smp97 May 14 '20 at 05:51