Java 从Scala中的列表创建映射

Java 从Scala中的列表创建映射,java,scala,scala-collections,Java,Scala,Scala Collections,我需要在scala中创建目录到文件的哈希映射,同时列出目录中的所有文件。如何在scala中实现这一点 val directoryToFile = awsClient.listFiles(uploadPath).collect { case path if !path.endsWith("/") => { path match { // do some regex matching to get directory & file names cas

我需要在scala中创建目录到文件的哈希映射,同时列出目录中的所有文件。如何在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]
作为参数传递给函数

您可以
过滤
,然后
折叠

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。大概是这样的:

val directoryToFile = (for {
    path <- awsClient.listFiles(uploadPath)
    if !path.endsWith("/")
    regex(dir, date) <- regex.findFirstIn(path)
} yield dir -> date).sortBy(_._2).toMap
val regex =  """(\d)-(\d)""".r
val paths = List("1-2", "3-4", "555")

for {

  // Hint to Scala to produce specific type
  _ <- Map("" -> "")

  // Not sure why your !path.endsWith("/") is not part of regex
  path@regex(a, b) <- paths
  if path.startsWith("1")

} yield (a, b)

//> scala.collection.immutable.Map[String,String] = Map(1 -> 2)
val directoryToFile=(用于{

path您可以尝试以下方法:

val directoryToFile = (for {
    path <- awsClient.listFiles(uploadPath)
    if !path.endsWith("/")
    regex(dir, date) <- regex.findFirstIn(path)
} yield dir -> date).sortBy(_._2).toMap
val regex =  """(\d)-(\d)""".r
val paths = List("1-2", "3-4", "555")

for {

  // Hint to Scala to produce specific type
  _ <- Map("" -> "")

  // Not sure why your !path.endsWith("/") is not part of regex
  path@regex(a, b) <- paths
  if path.startsWith("1")

} yield (a, b)

//> scala.collection.immutable.Map[String,String] = Map(1 -> 2)

listFiles
返回什么?@YuvalItzchakov Seq[String]这是目录中所有文件的绝对路径列表谢谢!那么“collect”呢方法,其中我是根据原始代码中的特定条件筛选出一些元素的?在使用
foldLeft
之前,您可以应用
filter
。编辑答案。谢谢!现在,我有一个小的更新:可能存在一种情况,即同一个目录可能有多个由日期表示的文件:“dir1/2016-01-01.txt”和“dir1/2013-01-01/txt”。在这种情况下,我希望hashmap只保留最新文件日期的值。如何使用“max”函数来实现这一点?
+
on
immutable。使用相同键的Map
将覆盖上一个条目。请参阅我的解决方案。我已经添加了您的“max”“函数。
sortBy
用于什么?
Map
在Scala中是无序的。您说过您只想要与每个目录关联的最后(最近)日期。这是sortBy语句的目的。如果您不需要它,也可以将其删除。”。