2

我有以下功能。它可以很好地打印我要存储的值。我想建立一个 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 -> st

4

3 回答 3

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
于 2012-08-30T23:13:05.740 回答
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)

于 2012-08-30T23:25:58.473 回答
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

类似的东西

于 2012-08-30T23:01:18.323 回答