[英]Convert List[(String,String)] to Map[String, Map[String,String]]
Let's say I have below List[(String, String)]: 假设我在List [(String,String)]下面:
List((recap_items[4].invoice_items[0].id,6),
(recap_items[4].invoice_items[1].id,7),
(recap_items[4].invoice_items[1].qty,1),
(recap_items[4].invoice_items[0].qty,1),
(recap_items[4].invoice_items[1].sur_key,19),
(recap_items[4].invoice_items[0].sur_key,17))
How could I convert that List into below Map? 我该如何将该列表转换为Map以下?
Map(
recap_items[4].invoice_items[0] -> Map(id -> 6, qty -> 1, sur_key -> 17),
recap_items[4].invoice_items[1] -> Map(id -> 7, qty -> 1, sur_key -> 19)
)
Or is there any better representation to kinda group that List ? 还是有一些更好的表示形式可以列出该列表?
EDIT 编辑
case class Recap(recap_id: String, recap_date: Date, submitted_id:String, edited_id: String, recap_items: List[Recap_items])
case class Recap_items(product_name: String, product_id: String, qty: Int, unit_name: String, unit_multiplier: Int, sys_qty: Int, invoice_items: List[Invoice_items])
case class Invoice_items(sur_key: Long, id: Long, qty: Int)
CURRENT APPROACH 当前的方法
Below is my current approach which gives me Map[String, List[String]]: 下面是我目前的方法,该方法为我提供了Map [String,List [String]]:
code: 码:
flash.data.filterKeys(_.startsWith("recap_items["+i+"].invoice_items")).toList.sortBy(x => x._1).map{
x => (x._1.split("""\.""").toList(1), x._2)
}.groupBy(_._1).mapValues{
x => x.map( v => v._2)
}
output: 输出:
Map(invoice_items[1] -> List(7, 1, 19),
invoice_items[0] -> List(6, 1, 17))
Any clue how to improve this code? 任何线索如何改进此代码?
Not sure why you want to convert everything into string (I mean, recap_items[4].invoice_items[1] instead of the actual item name). 不知道为什么要将所有内容都转换为字符串(我的意思是recap_items [4] .invoice_items [1]而不是实际的商品名称)。
If your input is a Recap
object then you can just do: 如果您的输入是Recap
对象,则可以执行以下操作:
val recap: Recap = ...
val map: Map[String, Map[String, String]] =
(for (
(recapItem, recapItemIndex) <- recap.recap_items.zipWithIndex;
(invoiceItem, invoiceItemIndex) <- recapItem.invoice_items.zipWithIndex
) yield {
s"recap_item[$recapItemIndex]invoiceItem[$invoiceItemIndex]" -> Map("id" -> s"$invoiceItem.id", "qty" -> s"$invoiceItem.qty", "sur_key" -> s"$invoiceItem.sur_key")
}).toMap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.