Home »
Scala
SortedMap addString() Method in Scala with Example
Here, we will see the working of addString() method in Scala. addString() is used as addelements of sortedMap to stringBuilder.
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.
StringBuilder is a class that is used to append the data inputted to the internal Buffer. It is used on mutable strings to perform operations.
SortedMap addString() Method
addString() is Scala is a method which is used to add the elements of sortedMap to a stringBuilder. Additionally, we can add a separator to the stringBuilder in Scala.
Syntax:
sortedMap_Name.addString(new StringBuilder())
Parameters: The method has two parameters. One is the stringBuilder container, another is an optional parameter which is a string to be added.
Return: The method returns a stringBuilder which contains the elements of the sortedMap.
Example 1: Program to illustrate the working of addString() method
import scala.collection.immutable.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
val stringBuilder = mySortedMap.addString(new StringBuilder())
println("The added string is " + stringBuilder)
}
}
Output:
The added string is JavaScript -> 6Ruby -> 8scala -> 5
Example 2: Program to illustrate the working of addString() method with adding separator
import scala.collection.immutable.SortedMap
object myObject {
def main(args: Array[String]) {
val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
val stringBuilder = mySortedMap.addString(new StringBuilder(), " , ")
println("The added string is " + stringBuilder)
}
}
Output:
The added string is JavaScript -> 6 , Ruby -> 8 , scala -> 5