您的位置:首页 > 其它

scala使用zip合并两个集合为二元组集合

2017-08-01 09:17 218 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐