scala使用zip合併兩個集合為二元組集合
阿新 • • 發佈:2018-12-23
tuple只能有tuple2到tuple22
Problem
你想要合併兩個有序集合成為一個鍵值對集合
Solution
使用zip方法合併兩個集合:
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的結果進行遍歷:
scala> for((wife,husband) <- couples){
| println(s"$wife is merried to $husband")
| }
Wilma is merried to Fred
Betty is merried to Barney
一旦你遇到類似於couples這樣的二元祖集合,你可以把它轉化為一個map,這樣看起來更方便:
scala> val couplesMap = couples.toMap
couplesMap: scala.collection.immutable.Map[String,String] = Map(Wilma -> Fred, Betty -> Barney)
Discussion
如果一個集合包含比另一個集合更多的元素,那麼當使用zip合併集合的時候,擁有更多元素的集合中多餘的元素會被丟掉。如果一個集合只包含一個元素,那麼結果二元祖集合就只有一個元素。
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後的結果反向操作:
scala> val (a,b) = productsWithPrice.unzip
a: scala.collection.mutable.IndexedSeq[String] = ArrayBuffer(breadsticks)
b: scala.collection.mutable.IndexedSeq[Int] = ArrayBuffer(4)