val files = new File("data").list()
val filtered = files.filter(name => name.contains("txn"))
val masterList = new ListBuffer[String]
for (file <- filtered) {
val lines = Source.fromFile(new File("data\\" + file), "UTF-16").getLines
val cleaned = lines.filter(!masterList.contains(_))
println("*" + cleaned.length)
cleaned.foreach(println(_))
println("**" + cleaned.length)
cleaned.foreach(masterList.append(_))
}
代码的输出如下
*175
**0
我不明白为什么我的列表消失了
cleaned
是一个迭代器。
scala> val cleaned = lines.filter(_!="")
cleaned: Iterator[String] = non-empty iterator
分配后立即非空。 scala 中的迭代器是一次性的 - 一旦你遍历它(例如通过应用length
方法)它变成空:
scala> cleaned.length
res0: Int = 13
scala> cleaned.length
res1: Int = 0
您可以通过转换为 List 或 Seq (惰性)来修复该行为:
scala> val lines=Source.fromFile("bla.txt").getLines
lines: Iterator[String] = non-empty iterator
scala> val cleaned = lines.filter(_!="").toSeq
cleaned: Seq[String] = Stream(first, ?)
scala> cleaned.length
res4: Int = 13
scala> cleaned.length
res5: Int = 13
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)