You iterate through the whole Map, which is O(n) and therefore slow as hell. Worse, you even recreate every element and put it into another element, which is even slower.
Why not just do:
scala> val map = Map(1 -> Set(5,3), 2 -> Set(7,3)) map: scala.collection.immutable.Map[Int,scala.collection.immutable.Set[Int]] = Map(1 -> Set(5, 3), 2 -> Set(7, 3)) scala> def updateMap[A, B](map: Map[A, Set[B]], key: A, value: B) = map + ((key, map.getOrElse(key, Set()) + value)) updateMap: [A, B](map: Map[A,Set[B]], key: A, value: B)scala.collection.immutable.Map[A,Set[B]] scala> updateMap(map, 1, 9) res0: scala.collection.immutable.Map[Int,Set[Int]] = Map(1 -> Set(5, 3, 9), 2 -> Set(7, 3))
And you probably want to introduce another type parameter B to the signature of updateMap to allow values of a different type than the one of the key.