简体   繁体   English

Java中与Scala通用的习惯用法,遍历/迭代Java列表到Scala列表

[英]Common idiom in Java to Scala, traverse/Iterate Java list into Scala list

I am processing a XML document and iterating through nodes. 我正在处理XML文档并遍历节点。 I want to iterate through the nodes and build a new List of some type. 我想遍历节点并构建某种类型的新列表。 How would I do this with Scala: 我将如何使用Scala做到这一点:

Here is my XML traverse code: 这是我的XML遍历代码:

  def findClassRef(xmlNode: Elem) = {

    xmlNode\"classDef" foreach { (entry) =>
        val name    = entry \ "@name"
        val classid = entry \ "@classId"
        println(name + "//" + classid)
    }
  }

Where the line of println is, I want to append elements to a list. println行所在的位置,我想将元素追加到列表中。

Map should work. 地图应该工作。 If you do not need exactly a List instance you can remove the toList. 如果您不需要一个List实例,则可以删除toList。

xmlNode \"classDef" map { (entry) =>
  val name    = entry \ "@name"
  val classid = entry \ "@classId"
  name + "//" + classid
} toList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM