构建Map [String,String]

时间:2012-08-30 22:46:46

标签: xml scala

我有以下功能。它适用于打印我想要存储的值。我想构建一个Map [String,String]

def storePlayerEntry(n: Node, moved: Boolean) = {

    moved match {
      // storing a current player record
      // rowkey = playerid
      case true => {
        //println("current: " + teamId + ":" + n)
        println("id: " + n \ "@uID")
        for (
          s <- Seq("first_name",
            "last_name",
            "known_name",
            "birth_date",
            "weight",
            "height",
            "jersey_num",
            "real_position",
            "real_position_side",
            "join_date",
            "country")
        ) {
          val stat = (n \\ "Stat").filter(_.attribute("Type").filter(_.toString() == s).isDefined)
          Option(stat.text) match {
            case Some(st) if (st == "") => // do nothing
            case Some(st) => println(st)
            case None => // do nothing
          }
        }
        //val ret = dataApi.upsertMulti("players", 
      }
      case false => {
        //println("old: " + teamId + ":" + n)            
      }
    }
  }

我正在避免声明地图然后只是添加方法,因为我确定在这里有更多的scala-ish要完成。

我正在寻找的地图将包含类似s - &gt;的内容。 ST

3 个答案:

答案 0 :(得分:2)

@jdevelop很接近。应该是这样的:

val x = (for (
              s <- Seq("first_name",
                "last_name",
                "known_name",
                "birth_date",
                "weight",
                "height",
                "jersey_num",
                "real_position",
                "real_position_side",
                "join_date",
                "country");
              val st = (n \\ "Stat").filter(_.attribute("Type").filter(_.toString() == s).isDefined).text if (st != "")
            ) yield (s -> st)).toMap

答案 1 :(得分:2)

这是一种更惯用的方法:首先我们制作一套我们关心的所有键:

val keys = Set(
 "first_name",
 "last_name",
 "known_name",
 "birth_date",
 "weight",
 "height",
 "jersey_num",
 "real_position",
 "real_position_side",
 "join_date",
 "country"
)

请注意,为了效率和逻辑,这可以在方法之外定义。

在方法中,我们使用Stat属性制作所有Type元素的地图,然后使用我们的集合过滤键:

  val stats: Map[String, String] = (n \\ "Stat").flatMap {
    s => s.attribute("Type").map(_.toString -> s.text)
  }.toMap.filterKeys(keys)

现在我们有一个从我们感兴趣的键到相应Stat元素的文本内容的映射。因此,如果我们的n看起来像这样:

<Player uID="john">
  <Stat Type="first_name">John</Stat>
  <Stat Type="last_name">Doe</Stat>
  <Stat Type="some_irrelevant_thing">blah</Stat>
</Player>

我们的结果将根据需要Map(first_name -> John, last_name -> Doe)

答案 2 :(得分:0)

(for (
      s <- Seq("first_name",
        "last_name",
        "known_name",
        "birth_date",
        "weight",
        "height",
        "jersey_num",
        "real_position",
        "real_position_side",
        "join_date",
        "country");
      val Some(st) = (n \\ "Stat").filter(_.attribute("Type").filter(_.toString() == s).isDefined)
      if (st != "")
    ) yield (s -> st)).toMap

类似的东西