【ALGORITHM】比較列表元素,並根據Scala中的邏輯建立[鍵值對或對映]

2020-12-22 ALGORITHM

我有一個包含以下資料的列表我必須比較列表中的元素並建立具有指定條件的對映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"
)

我有一大套最快的方法是什麼?

解決辦法

所以,你本質上想要反轉amap.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
      )
    }
}

出處

Have any Question?

Let us answer it!