【问题标题】:How to extract immutable from Map(String, List(String)) list using Functional programming in scala如何使用scala中的函数式编程从Map(String,List(String))列表中提取不可变
【发布时间】:2021-09-12 05:45:13
【问题描述】:
val filesMap = [/dir/one -> {text1.txt, text2.txt, command.txt}, /dir/two -> {text1.txt, text2.txt, command.txt}, /dir/three -> {text1.txt, text2.txt}} 

val allFiles = filesMap().toList

应该解析包含command.txt 文件的目录,其余的将被忽略。从上面的/dir/three 应该被忽略。然后我需要阅读 command.txt ,其中包含如下命令 Delete: 2 将两个最旧的文件插入到 allFiles 列表中。我已经有一种读取command.txt 文件并提取所有命令的方法,它的值映射commandMap。例如commandMap 如下所示。

commandMap = {Delete -> 2, Copy -> 2, Cut -> 2}
// method that extract commands from commands.txt to the map
def readCommandFile(pathToCommand: String): Map[String, Int] ={
      // som logic to extract list of commands from the text file
}

【问题讨论】:

  • @Jwvh 如果您还有其他问题,请告诉我?

标签: list scala dictionary collections functional-programming


【解决方案1】:

def isCommand: FileStatus => Boolean = f => /* add ur allCommandsInDatFile.contains(numberOfFiles)  */

def getIndex: FileStatus => Int = f => /* add ur Integer.parseInt(allCommandsInDatFile(numberOfFiles) */

fileMap.flatMap { 
  case (_, files) => files.find(isCommand) match { 
    case Some(file) => 
      val index = getIndex(file)
      files.takeRight(index)
    case None => files 
  } 
}

这会解决您的问题吗?

我编辑了一点。

【讨论】:

  • 如何添加多个参数,这里只包含 FileStatus => F
  • 你能详细说明你的allCommandsInDatFile.contains(numberOfFiles) 吗?从我的角度来看,这只是为了检查 keep command 是否小于 0 或大于列表长度。您可以轻松将此逻辑添加到getIndex: FileStatus => Int
  • 我做了类似你所说的,if(index != 0) files.takeRight(index) else None,但看起来过滤逻辑不起作用。
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多