August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to merge data from two sequential collections into a collection of key/value pairs.
Use the zip method to join two
sequences into one:
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 mencouples: List[(String, String)] = List((Wilma,Fred), (Betty,Barney))
This creates an Array of
Tuple2 elements, which is a merger of
the two original sequences.
This code shows one way to loop over the resulting collection:
scala>for ((wife, husband) <- couples) {|println(s"$wife is married to $husband")|}Wilma is married to Fred Betty is married to Barney
Once you have a sequence of tuples like couples, you can convert it to a Map, which may be more convenient:
scala> val couplesMap = couples.toMap
couplesMap: scala.collection.immutable.Map[String,String] =
Map(Wilma -> Fred, Betty -> Barney)If one collection contains more items than the other collection,
the items at the end of the longer collection will be dropped. In the
previous example, if the prices
collection contained only one element, the resulting collection will
contain only one Tuple2:
// three elements scala>val products = Array("breadsticks", "pizza", "soft drink")products: Array[String] = Array(breadsticks, pizza, soft drink) // one element scala>val prices = Array(4)prices: Array[Int] = Array(4) ...
Read now
Unlock full access