Scala贴图,按键合并多个贴图
我正在尝试合并具有相同密钥(帐户id)但不同值(如平均支出、最大支出金额和最小支出金额)的不同地图Scala贴图,按键合并多个贴图,scala,dictionary,functional-programming,Scala,Dictionary,Functional Programming,我正在尝试合并具有相同密钥(帐户id)但不同值(如平均支出、最大支出金额和最小支出金额)的不同地图 val a = Map(account1 -> 350.2, account2 -> 547.5, account3 -> 754.4) val b = Map(account1 -> 1250, account2 -> 3221.785, account3 -> 2900) val c = Map(account1 -> 50, account2 -
val a = Map(account1 -> 350.2, account2 -> 547.5, account3 -> 754.4)
val b = Map(account1 -> 1250, account2 -> 3221.785, account3 -> 2900)
val c = Map(account1 -> 50, account2 -> 21.5, account3 -> 12.7)
我想:
val d = Map(account1 -> (350.2, 1250 , 50), account2 -> (547.5, 3221.785 , 21.5), ... , ... )
我还想创建一个列表,如:
((account1,350.2, 1250 , 50), (account2, 547.5, 3221.785), ... )
任何帮助都会很好,非常感谢。如前所述
在我的情况下,帐户类型为字符串,在这种情况下,如何合并两个地图??非常感谢您的帮助。您是否尝试过使用字符串,但遇到了问题?
// convert maps to seq, to keep duplicate keys and concat
val merged = Map(1 -> 2).toSeq ++ Map(1 -> 4).toSeq
// merged: Seq[(Int, Int)] = ArrayBuffer((1,2), (1,4))
// group by key
val grouped = merged.groupBy(_._1)
// grouped: scala.collection.immutable.Map[Int,Seq[(Int, Int)]] = Map(1 -> ArrayBuffer((1,2), (1,4)))
// remove key from value set and convert to list
val cleaned = grouped.mapValues(_.map(_._2).toList)
// cleaned: scala.collection.immutable.Map[Int,List[Int]] = Map(1 -> List(2, 4))