Scala Tutorial - Learn How To Use Unzip3 Function With Examples
Overview
In this tutorial, we will learn how to use the unzip3 function with examples on collection data structures in Scala. The unzip3 function is applicable to both Scala's Mutable and Immutable collection data structures.
The unzip3 method will un-merge a collection consisting of elements as Tuple3 into three separate collections.
As per the Scala documentation, the definition of the unzip3 method is as follows:
def unzip3[A1, A2, A3](implicit asTriple: (A) ⇒ (A1, A2, A3)): (CC[A1], CC[A2], CC[A3])
The unzip3 method is a member of GenericTraversableTemplate trait.
Steps
1. How to initialize a Sequence of Tuple3 elements
In the previous Unzip Tutorial, we showed how to use the zip and unzip methods to merge and unmerge Tuple2 elements from and to collections.
In the example below, we will create a Sequence of Tuple3 elements to represent donut name, its price and a taste level.
println("Step 1: How to initialize a Sequence of Tuple3 elements")
val donuts: Seq[(String, Double, String)] = Seq(("Plain Donut",1.5,"Tasty"), ("Glazed Donut",2.0,"Very Tasty"), ("Strawberry Donut",2.5,"Very Tasty"))
println(s"Donuts tuple3 elements = $donuts")
You should see the following output when you run your Scala application in IntelliJ:
Step 1: How to initialize a Sequence of Tuple3 elements
Donuts tuple3 elements = List((Plain Donut,1.5,Tasty), (Glazed Donut,2.0,Very Tasty), (Strawberry Donut,2.5,Very Tasty))
2. How to call unzip3 function to unzip Tuple3 elements
Similar to the unzip method, Scala provides a convenient unzip3 method to unzip Tuple3 elements from a collection into three separate collections.
As shown in the example below, by calling unzip3 on the donuts Immutable Sequence from Step 1, we get back a Tuple3 type where each element is a collection for each of the Tuple3 elements. In other words, we have a Sequence for donut names, prices and taste level.
println("\nStep 2: How to call unzip3 function to unzip Tuple3 elements")
val unzipped: (Seq[String], Seq[Double], Seq[String]) = donuts.unzip3
println(s"Unzipped donut names = ${unzipped._1}")
println(s"Unzipped donut prices = ${unzipped._2}")
println(s"Unzipped donut taste = ${unzipped._3}")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to call unzip3 function to unzip Tuple3 elements
Unzipped donut names = List(Plain Donut, Glazed Donut, Strawberry Donut)
Unzipped donut prices = List(1.5, 2.0, 2.5)
Unzipped donut taste = List(Tasty, Very Tasty, Very Tasty)
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence of Tuple3 elements
- How to call unzip3 function to unzip Tuple3 elements
Tip
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will show you how to use the view function.