Someone else mentioned mapValues , but if I were you, I would do it like this:
scala> val m = Map(1 -> Seq(1), 2 -> Seq(2)) m: scala.collection.immutable.Map[Int,Seq[Int]] = Map(1 -> List(1), 2 -> List(2)) scala> m.map { case (k,Seq(v)) => (k,v) } res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)
Two reasons:
The mapValues method creates a representation of the Map result, which means that the function will be redistributed every time you access the element. If you do not plan to access each element exactly once or plan to only access a very small percentage of them, you do not want this recalculation to occur.
Using the case with (k,Seq(v)) ensures that an exception is thrown if the function ever sees a Seq that does not contain exactly one element. Using _(0) or _.head will throw an exception if there are null elements, but will not complain if you had more than one, which will most likely lead to mysterious errors later when things go missing without errors.
dhg source share