×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

SortedMap addString() Method in Scala

By IncludeHelp Last updated : November 14, 2024

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 Type

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]): Unit = {
        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]): Unit = {
        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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.