Scala zip/unzip function

Zip function is used to aggregate the contents of two lists into a single list of pairs.

Consider that, we have two lists one contain the list of tasks and another contains list of person names. We want to create another list contains person and task pair. Let see how we can use zip function to do this.

Refer the below example,


object ScalaMain {

  def main(args: Array[String]): Unit = {

    val taskList = List("task1", "task2", "task3")
    val personList = List("Peter", "John", "Patrick")

    val personWithTaskList = personList zip taskList

    personWithTaskList.foreach {
      case (person, task) =>
        println(s"$task is assigned to $person")
    }
  }
}


The output is given below,


task1 is assigned to Peter
task2 is assigned to John
task3 is assigned to Patrick

Unzip function will work as reverse of zip. Refer the below code and its output.



    val unzippedList = personWithTaskList unzip

    println(s"list of persons:${unzippedList._1}")
    println(s"list of tasks:${unzippedList._2}")


Output:


list of persons:List(Peter, John, Patrick)
list of tasks:List(task1, task2, task3)

As the “zip” function creates a pair, it will omit all the unpaired elements. Refer the below example,


object ScalaMain {

  def main(args: Array[String]): Unit = {

    val taskList = List("task1", "task2", "task3")
    val personList = List("Peter", "John", "Patrick", "Joe")

    val personWithTaskList = personList zip taskList

    personWithTaskList.foreach {
      case (person, task) =>
        println(s"$task is assigned to $person")
    }
  }

}


The output of the above program is given below,


task1 is assigned to Peter
task2 is assigned to John
task3 is assigned to Patrick


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s