加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么我的Scala列表会在以下代码中消失?

发布时间:2020-12-16 09:09:21 所属栏目:安全 来源:网络整理
导读: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
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

我不明白为什么我的名单消失了

解决方法

clean是一个迭代器.

scala> val cleaned = lines.filter(_!="")
cleaned: Iterator[String] = non-empty iterator

分配后,它是非空的. scala中的迭代器是单独使用的 – 一旦你遍历它(例如通过应用长度方法)它变为空:

scala> cleaned.length
res0: Int = 13

scala> cleaned.length
res1: Int = 0

您可以通过转换为List或Seq(lazy)来修复该行为:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读