Scala zip and zipWithIndex examples (with Stream)

If you’re interested in learning how to use the Scala zip and zipWithIndex methods, here are a few examples.

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 like this:

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 Stream class is deprecated, and has been replaced by the Scala 3 LazyList class.

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.