第十章 Scala 容器基础(二十三):使用zip合并两个集合为二元组集合

Problem

    你想要合并两个有序集合成为一个键值对集合scala

Solution

    使用zip方法合并两个集合:code

scala> val women = List("Wilma", "Betty")
women: List[String] = List(Wilma, Betty)

scala> val men = List("Fred", "Barney")
men: List[String] = List(Fred, Barney)

scala> val couples = women zip men
couples: List[(String, String)] = List((Wilma,Fred), (Betty,Barney))

    上面建立了一个二元祖集合,它把两个原始集合合并为一个集合。下面咱们来看下如何对zip的结果进行遍历:ip

scala> for((wife,husband) <- couples){
     |   println(s"$wife is merried to $husband")
     | }
Wilma is merried to Fred
Betty is merried to Barney

    一旦你遇到相似于couples这样的二元祖集合,你能够把它转化为一个map,这样看起来更方便:it

scala> val couplesMap = couples.toMap
couplesMap: scala.collection.immutable.Map[String,String] = Map(Wilma -> Fred, Betty -> Barney)

Discussion

    若是一个集合包含比另外一个集合更多的元素,那么当使用zip合并集合的时候,拥有更多元素的集合中多余的元素会被丢掉。若是一个集合只包含一个元素,那么结果二元祖集合就只有一个元素。
io

scala> val products = Array("breadsticks", "pizza", "soft drink")
products: Array[String] = Array(breadsticks, pizza, soft drink)

scala> val prices = Array(4)
prices: Array[Int] = Array(4)

scala> val productsWithPrice = products.zip(prices)
productsWithPrice: Array[(String, Int)] = Array((breadsticks,4))

    注意:咱们使用unzip方法能够对zip后的结果反向操做:table

scala> val (a,b) = productsWithPrice.unzip
a: scala.collection.mutable.IndexedSeq[String] = ArrayBuffer(breadsticks)
b: scala.collection.mutable.IndexedSeq[Int] = ArrayBuffer(4)
相关文章
相关标签/搜索