Scala tuple is a collection of items together of different data types. Scala tuple is immutable.
For example;
val s1 = (12,"Harry")
Here we are declaring a tuple s1 that holds student id of integer type and student name of String data type.
The above tuple s1 can also be declared as;
val s1 = new Tuple2(12,"Harry")
The type of the tuple depends upon the number of elements contained and the data types of those elements. The type (12,”Harry”) is of type Tuple2[Int,String].
The upper limit for the number of elements that a tuple can contain is 22. For each tuple of TupleN type, where 1
val m1 = (20,12,16,4)
Elements of the tuple t1 can be accessed as m1._1
for first element, m1._2
for second element and so on.
val mul = m1._1* m1._2*m1._4
We are accessing the first, second and fourth element of tuple m1 and multiplying the elements storing the result in variable mul.
In all our earlier examples, we have used Scala shell to execute programs or compile/run scala code from command line. But today we will use the Scala eclipse IDE for executing the program. You can download the Eclipse IDE for Scala from https://scala-ide.org/download/sdk.html according to your operating system.
Open the Scala Eclipse IDE and create new project as;
Select File → New → Scala Project. Enter the project name and click on finish.
Right click on the project and select New Scala object and enter the object name and click on finish.
Now enter the code in IDE as shown below.
Multiply.scala
object Multiply {
def main(args: Array[String]) {
val m1 = (20, 12, 16, 4)
val mul = m1._1 * m1._2 * m1._4
println("Result is : " + mul)
}
}
Now run the application as Run As → Scala Project. Below image shows the output produced.
Iterating over the Tuple
Tuple.productIterator()
method iterates through all the elements of the tuple.
Let us see an example of how to print the student names iterating over the tuple
Write the code in scala object Iterate.scala
as;
object Iterate {
def main(args: Array[String]) {
val names = ("John","Smith","Anderson","Steve","Rob")
names.productIterator.foreach{ i =>println("Value = " + i )}
}
}
We are creating a tuple names and use the productIterator method to iterate and print the elements of the tuple.
Now run it as Scala application and see the following output;
Student Names are :
John
Smith
Anderson
Steve
Rob
Swapping the Tuple elements
The Tuple.swap
method is used to swap the elements of the tuple.
object Swap {
def main(args: Array[String]) {
val id = new Tuple2(12,34)
println("Swapped Tuple Id is:"+id.swap)
}
}
Output produced will be Swapped Tuple Id is:(34,12)
Conversion to String
The Tuple.toString()
method concatenates all the elements of the tuple into a string.
For Example type the following code in scala object StringConverstion.scala
as
object StringConversion {
def main(args: Array[String]) {
val student = new Tuple3(12, "Rob", "IT")
println("Concatenated String: " + student.toString())
}
}
Output:
Concatenated String: (12,Rob,IT)
Maps in Scala
A map can be defined as a collection of key/value pairs. Keys are unique but the values need not be unique.
Maps are of two types mutable and immutable. The difference between mutable and immutable is that when the object is immutable the object itself cannot be changed. Import scala.collection.mutable.Map
to use the mutable map set. By default Scala uses immutable map.
Consider an example of map with key as student ids and student names as the value
val student = Map(12 -> "Reena", 13 -> "Micheal" , 14 -> "Peter")
Basic Operations on Map:
The basic methods supported are
keys: Returns an iterator containing each key in a map
values: Returns an iterator containing each value in a map
isEmpty: Returns true if the map is empty
Consider an example for the basic operations on Map.
Create the scala object MapOperations.scala
as
object MapOperations {
def main(args: Array[String]) {
val student = Map(12 -> "Reena", 13 -> "Micheal", 14 -> "Peter")
val marks: Map[String, Int] = Map()
println("Keys : " + student.keys)
println("Values : " + student.values)
println("Check if student is empty : " + student.isEmpty)
println("Check if marks is empty : " + marks.isEmpty)
}
}
Below is the output produced when executed as Scala application.
Keys : Set(12, 13, 14)
Values : MapLike(Reena, Micheal, Peter)
Check if student is empty : false
Check if marks is empty : true
Concatenating Maps
The ++ operator or Map.++() operator is used to concatenate two or more maps but the duplicate keys will be removed.
Consider an example of how to concatenate maps below.
object ConcatMaps {
def main(args: Array[String]) {
val stud1 = Map(12 -> "Reena", 13 -> "Micheal" , 14 -> "Peter")
val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")
var student = stud1 ++ stud2
println( "stud1 ++ stud2 : " + student )
val stu = stud1.++(stud2)
println( "stud1.++(stud2)) : " + stu )
}
}
Output produced by above program:
stud1 ++ stud2 : Map(14 -> Peter, 13 -> Micheal, 17 -> Steve, 12 -> Reena, 16 -> Mark, 15 -> Russel)
stud1.++(stud2)) : Map(14 -> Peter, 13 -> Micheal, 17 -> Steve, 12 -> Reena, 16 -> Mark, 15 -> Russel)
Print keys and values from a Map
foreach
loop is used to iterate through all the key and value pairs in a map.
For example create a scala object KeyValues.scala as;
object KeyValues {
def main(args: Array[String]) {
val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")
stud2.keys.foreach{ i =>
print( "Key = " + i )
println(" Value = " + stud2(i) )}
}
}
Output:
Key = 15 Value = Russel
Key = 16 Value = Mark
Key = 17 Value = Steve
Check for a key in a Map
The Map.contains
method to test if a given key exists in the map or not.
For example create a scala object Keyexists.scala
as;
object Keyexists {
def main(args: Array[String]) {
val stud2 = Map(15 -> "Russel", 16 -> "Mark" , 17 -> "Steve")
if( stud2.contains( 15 )){
println("Student Id 15 exists with value :" + stud2(15))
}else{
println("Student Id with 15 does not exist")
}
if( stud2.contains( 16 )){
println("Student Id 16 exists with value :" + stud2(16))
}else{
println("Student Id 16 does not exist")
}
if( stud2.contains( 17 )){
println("Student Id 17 exists with value :" + stud2(17))
}else{
println("Student Id 17 does not exist")
}
if( stud2.contains( 18 )){
println("Student Id 18 exists with value :" + stud2(18))
}else{
println("Student Id 18 does not exist")
}
}
}
Output:
Student Id 15 exists with value :Russel
Student Id 16 exists with value :Mark
Student Id 17 exists with value :Steve
Student Id 18 does not exist
Scala Map methods
Some of the other useful methods are;
def ++(a: Map[(X, Y)]): Map[X, Y] → Returns a new map containing mappings of this map and those provided by a.
def -(e1: X, e2: X, elems: X*): Map[X, Y] → Returns a new map containing all the mappings of this map except mappings with a key equal to e1, e2 or any of elems.
def count(a: ((X, Y)) => Boolean): Int → Counts the number of elements
def max: (X,Y) → Finds the largest element in the map.
def min: (X,Y) → Finds the smallest element in the map
That’s all for Scala Tuples and Maps, we will look into Option and Iterators in coming post.