简体   繁体   中英

How can I convert a class to Map[X, (List[Y], Z)]?

I have List collection with data below:

case class Expense_detail(po_id: Long, supplier_id: String, price: String)

Expense_detail(1,"S00001","1000.0"), 
Expense_detail(2,"S00001","2000.0"), 
Expense_detail(3,"S00002","3,000.0"), 
Expense_detail(4,"S00003","4,000.0")

Is it possible to map it into below Map collection:

"S00001" -> ((1,2), "3000.0")
"S00002" -> ((3), "3000.0")
"S00003" -> ((4), "4000.0")

Yes with groupBy an mapValues .

case class ExpenseDetail(poId: Long, supplierId: String, price: String)

val details : List[ExpenseDetail] = ...

details.
 groupBy( _.supplierId ).
 mapValues( details => ( (details.map(_.poId)), details.map(_.price.toInt).sum ))

This should work. I changed the naming to honor the Scala/Java best practices to use CamelCase instead of snake_case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM