你想要合併兩個有序集合成爲一個鍵值對集合scala
使用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)
若是一個集合包含比另外一個集合更多的元素,那麼當使用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)