Scala Collections : Map and Tuple with Code Examples

Same as Java Map, Scala Map is the collection(Iterable) of various key and value pairs in Scala Collections. All keys in Map are unique and associated with a value. Same as List and Set, Scala Maps are also having two types immutable and mutable.Here is the Syntax for creating Map in Scala,

By default Scala uses Map class from scala.collection.immutable package. In case you want to use Mutable Map, you need use it from scala.collection.mutable package.

Let’s have some code examples of immutable Map.

You can also run above examples using Mutable Map.

What are Tuples in Scala?

Tuple is the collection class in Scala which can hold multiple values with same or different types together.

For example if you want a common reference for student name and roll-number you can create a tuple using syntax (studentName, studentRollNo)

If you have observed in above two tuples the class type of student is scala.Tuple2 and class type of address is scala.Tuple3. These is how you can extend your tuple up-to 22 values at a time and you respective class type will change from Tuple2 to Tuple22 in Scala.

How to access values of Tuple in Scala?

You can access the the respective elements of tuple using _1, _2 up-to _22. For example in our above examples if we want to access the student name and roll number which are on index 1 and 2 respectively, you can use following syntax.

This is how we can assign values of tuples to multiple variables in one line.

Now we just want to extract student name and pin information. This is how we can do that.

I hope you enjoyed this article. Please give your valuable comments on this.

References

Leave a Reply

Your email address will not be published. Required fields are marked *