我有一个包含以下数据的列表。我必须比较列表的元素并创建具有指定条件的地图。 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"
)
我有一个很大的设置,最快的方法是什么?
答案 0 :(得分: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 :(得分: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)
组合比赛。
答案 2 :(得分:0)
如果我们可以假设json模式的条目总是针对csv,那么一种方法可能是在排序后对列表进行分区和压缩。
val (csvs, jsons) = input.partition (n => n.endsWith (".csv"))
csvs.sorted.zip(jsonSchemas.sorted)