比较List of List并根据Scala中的逻辑创建[键值对或映射]

问题描述 投票:0回答:3

我有一个包含以下数据的列表。我必须比较列表的元素并创建具有指定条件的地图。 SFTP.csv应映射到/dev/sftp/SFTP_schema.json与其他元素相同。

List[String] = List(
  "/dev/sftp/SFTP.csv" , 
  "/dev/sftp/test_schema.json" , 
  "/dev/sftp/SFTP_schema.json",
  "/dev/sftp/test.csv"
)

我有一个很大的设置,最快的方法是什么?

algorithm scala scala-collections
3个回答
1
投票

所以,你基本上想要反转一个map.flatMap{ case (k, v) => List(k, v)) }?这看起来很有趣......这个怎么样?:

val input = List(
  "/dev/sftp/SFTP.csv" , 
  "/dev/sftp/test_schema.json" , 
  "/dev/sftp/SFTP_schema.json",
  "/dev/sftp/test.csv"
)

val res = input.
  groupBy(s => s.
    split("/").
    last.
    replaceAll("\\.csv","").
    replaceAll("_schema\\.json","")
  ).
  map { 
    case (k, v1 :: v2 :: Nil) => 
      if (v1.endsWith("csv")) (v1, v2)
      else (v2, v1)
    case sthElse => throw new Error(
      "Invalid combination of csv & schema.json: " + sthElse
    )
  }

println(res)

生产:

// Map(
//   /dev/sftp/SFTP.csv -> /dev/sftp/SFTP_schema.json, 
//   /dev/sftp/test.csv -> /dev/sftp/test_schema.json
// )

作为方法:

def invertFlatMapToUnionKeyValue(input: List[String]): Map[String, String] = {
  input.
    groupBy(s => s.split("/").last.
      replaceAll("\\.csv","").
      replaceAll("_schema\\.json",""
    )).
    map { 
      case (k, v1 :: v2 :: Nil) => 
        if (v1.endsWith("csv")) (v1, v2)
        else (v2, v1)
      case sthElse => throw new Error(
        "Invalid combination of csv & schema.json: " + sthElse
      )
    }
}

1
投票

您可以根据谓词将列表分区为2:

val (csvs, jsons) = input.partition (n => n.endsWith (".csv"))
// csvs: List[String] = List(/dev/sftp/SFTP.csv, /dev/sftp/test.csv)
// jsons: List[String] = List(/dev/sftp/test_schema.json, /dev/sftp/SFTP_schema.json)

然后迭代名称,剥离.csv和_schema.json:

for (c <- csvs;
  j <- jsons;
  if (c.substring (0, c.length - 4) == j.substring (0, j.length - 12))) yield 
    (c, j) 

结合比赛。


0
投票

如果我们可以假设json模式的条目总是针对csv,那么一种方法可能是在排序后对列表进行分区和压缩。

val (csvs, jsons) = input.partition (n => n.endsWith (".csv"))
csvs.sorted.zip(jsonSchemas.sorted)
© www.soinside.com 2019 - 2024. All rights reserved.