Home »
Scala
SortedMap mkString() Method in Scala with Example
Here, we will see the usage of the mkString() method on sortedMap. It is used to convert sortedMap to string in Scala. Here, we will see the working and examples of the mkString() method.
Submitted by Shivang Yadav, on January 24, 2021
Map is a collection that stores its elements as key-value pairs, like a dictionary. SortedMap is a special type of map in which elements are sorted in ascending order.
String is a sequence of characters. In Scala, the String object is immutable.
SortedMap mkString() Method
mkString() method on sortedMap is used to convert the given sortedMap into a string. There is an additional option to add a separator to the converted string.
Syntax:
sortedMap_name.mkString()
Parameter: The method accepts an optional parameter which is a string to be added as the separator while converting to string.
Return Value: It a string which contains the elements of the sortedMap.
Example 1: Program to illustrate the working of mkString method
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
println("Sorted Map: " + mySortedMap)
val sortedMapString = mySortedMap.mkString
println("String converted Sorted Map: " + sortedMapString)
}
}
Output:
Sorted Map: TreeMap(JavaScript -> 6, Ruby -> 8, scala -> 5)
String converted Sorted Map: JavaScript -> 6Ruby -> 8scala -> 5
Example 2: Program to illustrate the working of mkString method
import scala.collection.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
println("Sorted Map: " + mySortedMap)
val sortedMapString = mySortedMap.mkString(" , ")
println("String converted Sorted Map: " + sortedMapString)
}
}
Output:
Sorted Map: TreeMap(JavaScript -> 6, Ruby -> 8, scala -> 5)
String converted Sorted Map: JavaScript -> 6 , Ruby -> 8 , scala -> 5