×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

SortedMap mkString() 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.

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()

Parameters

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

Comments and Discussions!

Load comments ↻





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