从 Scala 中的列表创建地图 [英] create a map from list in Scala

查看:58
本文介绍了从 Scala 中的列表创建地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我列出目录中的所有文件时,我需要在 Scala 中创建一个目录到文件的 HashMap.我怎样才能在 Scala 中实现这一点?

I need to create a HashMap of directory-to-file in scala while I list all files in the directory. How can I achieve this in scala?

val directoryToFile = awsClient.listFiles(uploadPath).collect {
  case path if !path.endsWith("/") => {
    path match {
      // do some regex matching to get directory & file names
      case regex(dir, date) => {
          // NEED TO CREATE A HASH MAP OF dir -> date. How???
      }
      case _ => None
    }
  }
}

方法listFiles(path: String)返回作为参数传递的path中所有文件的绝对路径的Seq[String]到函数

The method listFiles(path: String) returns a Seq[String] of absolute path of all files in the path passed as argument to the function

推荐答案

你可以filter然后foldLeft:

val l = List("""/opt/file1.txt""", """/opt/file2.txt""")
val finalMap = l
                .filter(!_.endsWith("/"))
                .foldLeft(Map.empty[String, LocalDateTime])((map, s) =>
  s match {
    case regex(dir, date) => map + (dir -> date)
    case _ => map
  }
)

这篇关于从 Scala 中的列表创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆