比较列表的元素并根据 Scala 中的逻辑创建 [键值对或映射]

Compare the Elements of List and creating a [key value Pairs or Maps] based on logic in Scala

我有一个包含以下数据的列表。我必须比较列表的元素并创建具有指定条件的地图。 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"
)

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

那么,您本质上是想反转 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
      )
    }
}

您可以根据谓词将列表分成 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) 

合并匹配项。

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

val (csvs, jsons) = input.partition (n => n.endsWith (".csv"))
csvs.sorted.zip(jsonSchemas.sorted)