我有一个清单收集如下:
PO_ID _ Product_ID _
PO123 - P001 -项目1- 10
PO123 - P001 -项目1- 10
PO123 - P002 -项目2-2- 30
PO123 - P002 -项目2- 10
如何将其转换为如下集合:
PO_ID _ Product_ID _
PO123 - P001 -项目1- 20
PO123 - P002 -项目2-4
谢谢你的帮助
发布于 2014-04-07 06:12:56
我真的不明白你的“地图”是如何定义的,在我看来,它更像是一个列表。
下面是如何使用列表来实现的方法,如果您想使用Map来完成它,您只需稍微修改代码,因为下面使用的函数都是从可迭代基类继承的(常见于映射和列表)。
val data = List(("PO123", "P001", "Item 1", 10),
("PO123", "P001", "Item 1", 10),
("PO123", "P002", "Item 2", 30),
("PO123", "P002", "Item 2", 10))
data.groupBy( product => (product._1, product._2, product._3))
.map {
case (productInfo, products) => {
val total = products.foldLeft(0)((sum,elt) => sum + elt._4)
(productInfo._1,productInfo._2,productInfo._3,total)
}
}其结果将是:
scala.collection.immutable.Iterable[(String, String, String, Int)] =
List((PO123,P001,Item 1,20), (PO123,P002,Item 2,40))发布于 2014-04-07 06:42:51
有这样的东西会很好
case class Document(poID: String, productID: String, name: String, qty: Int)那你就可以
var list2 = list.groupBy(doc => doc.productID)这给了Map[String,ListDocument]。现在您可以用以下方法来映射它:
list2.map(stringListTuple => stringListTuple._2.foldLeft(Document("","","",0)){
(acc: Document,curr: Document) => Document(curr.poID, curr.productID, curr.name,curr.qty + acc.qty)
}).toList.sortBy(el => el.productID)它能工作,但我相信你可以做得更漂亮:)
https://stackoverflow.com/questions/22904283
复制相似问题