从Scala中的列表创建一个映射

时间:2016-11-06 15:24:16

标签: java scala scala-collections

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

@Embeddable
public class DocID implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Column(name = "DocName")
    @JsonProperty
    @NotEmpty
    protected  String docName;


    @Column(name = "DocVersion")
    @JsonProperty
    @NotEmpty
    protected  String docVersion;

 // getters, setters ,equals, hashCode
}

方法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)作为函数传递的Seq[String]中所有文件的绝对路径{/ 1}}

3 个答案:

答案 0 :(得分:0)

您可以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
  }
)

答案 1 :(得分:0)

尝试编写更多惯用的Scala。像这样:

./del_last.py *.fq

答案 2 :(得分:-1)

您可以尝试这样的事情:

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)

如果您需要max稍微复杂一点:

val regex =  """(\d)-(\d)""".r
val paths = List("1-2", "3-4", "555", "1-3")

for {
  (_, ps) <-
    ( for {
        path@regex(a, b) <- paths
        if path.startsWith("1")
      } yield (a, b)
    ).groupBy(_._1)
} yield ps.maxBy(_._2)

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