我有一個類:結合自定義類型的2個向量,返回1矢量
case class Custom(label: String, num: Long)
給定這兩個列表:
val l1 = Vector(Custom("a", 1), Custom("aa", 1))
val l2 = Vector(Custom("a", 1))
我希望獲取的結果列表:
val l3 = Vector(Custom("a", 2), Custom("aa", 1))
我試過用這樣的摺疊:
l1.foldLeft(l2)((acc: List[Custom], el: Custom) => {
val itemWithIndex: Option[(Custom, Int)] = acc.zipWithIndex.find(_._1.label == el.label)
itemWithIndex match {
case Some(x) => acc.updated(x._2, Custom(el.label, acc(x._2).num + el.num))
case None => el :: acc
}
})
該實現迭代累加器(l2
)3次,並且l1
一次。我正在尋找更有效的解決方案。
很酷。你有什麼嘗試? – Jubobs
累加器起始位置爲第二個列表的foldLeft。然後,對於第一個列表中的每個項目,檢查它是否存在,是否存在,添加值,否則將值作爲新元素插入。這不是非常有效。遍歷整個列表以檢查是否存在某個東西,然後再次獲取它的位置。 – soote
編輯你的問題,並在那裏解釋你的方法;讓你的問題自成一體。 – Jubobs