不減少的樣子:
scala> val m1 = List("a"->1,"b"->2).groupBy(_._1)
m1: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,2)), a -> List((a,1)))
scala> val m2 = List("a"->3,"b"->4).groupBy(_._1)
m2: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,4)), a -> List((a,3)))
scala> m1 map { case (k,v) => (k, v ++ m2(k)) }
res0: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,2), (b,4)), a -> List((a,1), (a,3)))
或可能!(m2 contains k)
:
scala> m1 map { case (k,v) => (k, (m2 get k) map (v ++ _) getOrElse v) }
res1: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,2), (b,4)), a -> List((a,1), (a,3)))
反之亦然:
scala> val m2 = List("a"->3,"b"->4,"c"->5).groupBy(_._1)
m2: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,4)), a -> List((a,3)), c -> List((c,5)))
scala> type M = Map[String,List[(String, Int)]]
defined type alias M
scala> def r(m1: M, m2: M) = (m1.keySet ++ m2.keySet).toList map (k => (k, m1.getOrElse(k,Nil) ++ m2.getOrElse(k,Nil))) toMap
warning: there was one feature warning; re-run with -feature for details
r: (m1: M, m2: M)scala.collection.immutable.Map[String,List[(String, Int)]]
scala> r(m1,m2)
res4: scala.collection.immutable.Map[String,List[(String, Int)]] = Map(b -> List((b,2), (b,4)), a -> List((a,1), (a,3)), c -> List((c,5)))
美麗。這基本上是我要去的。 – acjay 2014-09-27 13:27:44