Bla...
Bla...

Reputation: 7288

Convert List[(String,String)] to Map[String, Map[String,String]]

Let's say I have below 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(
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]]:

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?

Upvotes: 0

Views: 493

Answers (1)

NSF
NSF

Reputation: 2549

Not sure why you want to convert everything into string (I mean, recap_items[4].invoice_items[1] instead of the actual item name).

If your input is a Recap object then you can just do:

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

Upvotes: 1

Related Questions