在scala中清除Map

piv4azn7  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(373)

问题陈述:
当我试图清除Map列时,处理程序Map的列部分也会被清除。有办法避免吗?

def getTransformations(configuration: NodeSeq) {
var id: Int = 0
var methodCall: String = ""
val completeTransformation = Map[Int, Map[String, Map[String, String]]]()
val transformationsMap = Map[Int, Map[String, Map[String, String]]]()
val handlers = Map[String, Map[String, String]]()
val columns = Map[String, String]()

for (transformations <- configuration \\ "transformations") {
  for (transformation <- transformations \\ "transformation") {
    id += 1
    for (handler <- transformation \\ "handler") {
       for (input <- handler \\ "input") {
           columns.+=(((input \\ "@name").mkString) -> input.text)
      }
      handlers(handler.attribute("type").mkString) = columns
      columns.clear()
    }
    transformationsMap(id) = handlers
    handlers.clear()
   }
 }
transformationsMap
}

示例:如图所示,处理程序Map是使用列Map构建的
当columns.clear被执行时,它在处理程序Map中的值也被清除

wwtsj6pe

wwtsj6pe1#

handlers(handler.attribute("type").mkString) = columns
columns.clear()

你设置的只是参考 columnshandlers 不是价值观。一旦你清理了 columns ,您正在从的内存中删除值 columns 参考和输入 handlers 你提到的地方 columns 也反映了这种变化。全都是。为避免此问题,请将 columns 并分配给 handler .

handlers(handler.attribute("type").mkString) =  collection.mutable.Map[String,String]() ++= columns

它取决于你,你想要可变或不变的Map,同时创建新的副本。

yptwkmov

yptwkmov2#

fwiw,“scala”写你在这里要做的事情的方式是这样的:

val transformationsMap = (configuration \\ "transformations")
    .flatMap(_ \\ "transformation") 
    .zipWithIndex
    .map { case (trf, idx) => (idx+1) -> trf }
    .toMap
    .mapValues(_ \\ "handler)
    .mapValues {
      _.map { h => h.attribute("type").mkString -> (h \\ "input") }
       .toMap
       .mapValues { 
         _.map { in => (in \\ "@name".mkString) -> in.text }
           .toMap
       }                 
    }

相关问题