The zip and zipWithIndex methods on Scala collections classes can be really when you want to merge two Scala sequences, such as two List, Sequence, Vector, ArrayBuffer or Array sequences into one new sequence. In this short tutorial I’ll show how to use these two methods.
Scala’s zipWithIndex
I’ve known about using Scala’s zipWithIndex method for quite some time. It’s available on Scala sequence classes, and I use it in for loops to replace counters, and it works as shown in this REPL example:
scala> List("a", "b", "c").zipWithIndex
res0: List[(String, Int)] = List((a,0), (b,1), (c,2))
I learned about using zip along with Stream last night while reading Joshua Suereth’s book, Scala In Depth. It works like this:
scala> List("a", "b", "c") zip (Stream from 1)
res1: List[(String, Int)] = List((a,1), (b,2), (c,3))
Both of these approaches are cool.
Using zip and zipWithIndex in a Scala 'for' loop
To see how to use these methods with a Scala for loop, see my tutorial, How to use zipWithIndex or zip to create for loop counters.
Scala 3 Update: The Scala 3
Streamclass is deprecated, and has been replaced by the Scala 3LazyListclass.
The Scaladoc
The Scaladoc describes the zip method like this:
Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.
It describes the zipWithIndex method like this:
Zips this list with its indices. Returns: A new list containing pairs consisting of all elements of this list paired with their index. Indices start at 0.
For more information, see the documentation for the zip and zipWithIndex methods, which you can find on Scala collection classes, such as List.
| this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |