0
votes

I am very new to scala, and want to create a hash map with the key being a candidate, and value being number of votes. Something like this: {(1:20),(2:4),(3:42),..}.

I`ve attempted with the following code:

 val voteTypeList = textFile.map(x=>x(2)) //String array containing votes: [3,4,2,3,2,1,1,1,9,..]

 var voteCount:Map[String,Int] = Map()

 voteTypeList.foreach{x=>{

     if (voteCount.contains(x)){ //Increment value
       var i: Integer = voteCount(x)
       voteCount.updated(x, i+1)
      // print(voteCount(x))
     }
     else{ //Create new key-value pair
     //  println(x)
       voteCount += (x -> 1) 

   }}}

 print(voteCount.size)

But the voteCount does not get created and .size returns 0.

Thank you!

2

2 Answers

1
votes

The problem you're encountering is caused by using a var to hold an immutable Map. Change that to a val holding a mutable Map and it works.

val voteCount:collection.mutable.Map[String,Int] = collection.mutable.Map()

Having said that, there are a number of other issues with the code that makes it non-idiomatic to the Scala way of doing things.

What you really want is something closer to this.

val voteCount = voteTypeList.groupBy(identity).mapValues(_.length)
0
votes

Jwvh's answer is idiomatic but non-obvious and, if the list has very large numbers of duplicates, memory-heavy.

You might also consider the literal-minded (yet still Scalarific) way of doing this:

 val voteCount = voteTypeList.foldLeft(Map(): Map[Int, Int]) { (v, x) =>
    v + (x -> (v.getOrElse(x, 0) + 1))
  }