在功能上合并多个地图

时间:2015-08-21 16:36:48

标签: scala

我正在合并这些地图:

val map1 : Map[String, String] = Map("four" -> "1", "three" -> "2");
val map2 : Map[String, String] = Map("four" -> "3", "three" -> "4");
val map3 : Map[String, String] = Map("four" -> "5", "three" -> "6");
val map4 : Map[String, String] = Map("four" -> "7", "three" -> "8");

使用循环和可变变量。

我不确定如何编写功能实现?

完整代码:

object tryout extends App {

val map1 : Map[String, String] = Map("four" -> "1", "three" -> "2");
val map2 : Map[String, String] = Map("four" -> "3", "three" -> "4");
val map3 : Map[String, String] = Map("four" -> "5", "three" -> "6");
val map4 : Map[String, String] = Map("four" -> "7", "three" -> "8");

val mapList : List[Map[String , String]] = List(map1 , map2 , map3 , map4)

val mergedMap: Map[String, List[String]] = Map("three" -> List("2","4","6","8") , 
                    "four" -> List("1","3","5","7"));

 val map = new scala.collection.mutable.HashMap[String,ListBuffer[String]]()
mapList.map(m => {

  m.map(m2 => {
    if(map.contains(m2._1)){
      val lb = map.get(m2._1).get
      lb += m2._2
    }
    else {
      map.put(m2._1, ListBuffer(m2._2))
    }
  })


})

map.foreach(m => println(m._1+","+m._2.mkString(",")))

}

1 个答案:

答案 0 :(得分:4)

这是一个单行,但你可以随意分解:

mapList.flatten.groupBy(_._1).mapValues(x => x.map(y => y._2))

结果:

res0: scala.collection.immutable.Map[String,List[String]] = 
Map(three -> List(2, 4, 6, 8), four -> List(1, 3, 5, 7))

在函数式编程中,避免了显式循环;我们尝试使用像flatMap, map这样的组合器来实现相同的目标......另外,如果你开始将Scala中的Map想象为2元组(它就在下面),那么处理它们就变成了在我看来更直观。这个->只是在Prelude中定义的,可以让Map定义变得更容易。