[英]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)
组合比赛。
如果我们可以假设某csv始终有一个json模式条目,则一种方法是在排序后对列表进行分区和压缩。
val (csvs, jsons) = input.partition (n => n.endsWith (".csv"))
csvs.sorted.zip(jsonSchemas.sorted)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.