如何合并 - 留下两个列表?

时间:2015-11-13 23:40:08

标签: scala

假设我有两个案例类:

case class LineItem(name: String, price:Int, discount:Discount)
case class Discount(amount:Int, reason:String)

我有订单项列表:

L1,L2,L3

和折扣清单:

D1,D2

如何将折扣合并到订单项列表中?

我最初想过只是压缩它们并映射但是从压缩列表中删除了L3。

3 个答案:

答案 0 :(得分:2)

我首先将折扣转换为Option[Discount]列表,将列表填入None s,压缩并映射:

//items: List[LineItem], discounts: List[Discount]
val discOptions = discounts.map(Some(_)).padTo(items.length, None)

items.zip(discOptions) map {
  case (item, Some(disc)) => item.copy(discount = disc)
  case (item, None) => item
}

答案 1 :(得分:0)

首先使用 List.fill(lineItems.size() - discounts.size())(折扣(0,"")以#34填写折扣; null"折扣直到它与订单项长度匹配,然后是zip,然后是map。

答案 2 :(得分:0)

zipLeft实施类似于zipAll,但忽略了右List中的额外元素。

def zipLeft[A, B](left: List[A], right: List[B], thatElem: B): List[(A, B)] = {
    val b = scala.collection.mutable.ListBuffer.empty[(A, B)]
    val these = left.iterator
    val those = right.iterator
    while (these.hasNext && those.hasNext)
      b += ((these.next(), those.next()))
    while (these.hasNext)
      b += ((these.next(), thatElem))
    b.toList
}
val lst1 = List(1,2,3)
val lst2 = List(4,5)
zipLeft(lst1,lst2,0)//List((1,4),(2,5),(3,0))