Reputation: 47051
In Haskell, there is a function called fromListWith which can generate a Map from a function (used to merge values with the same key) and a list:
fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
The following expression will be evaluated to true
:
fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
In Scala, there is a similar function called toMap
on List
objects , which can also convert a list to a Map, but it can't have a parameter of function to deal with duplicated keys.
Does anyone have ideas about this?
Upvotes: 8
Views: 296
Reputation: 14224
Apart from using scalaz
you could also define one yourself:
implicit class ListToMapWith[K, V](list: List[(K, V)]) {
def toMapWith(op: (V, V) => V) =
list groupBy (_._1) mapValues (_ map (_._2) reduce op)
}
Here is a usage example:
scala> val testList = List((5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a"))
scala> testList toMapWith (_ + _)
res1: scala.collection.immutable.Map[Int,String] = Map(5 -> aba, 3 -> ba)
Upvotes: 11