torjussa torjussa - 8 months ago 42
Scala Question

Adding key-value pairs to Map in scala

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 =>x(2)) //String array containing votes: [3,4,2,3,2,1,1,1,9,..]

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


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)



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

Thank you!


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)