SortedMap toArray() in Scala Method with Example

In this tutorial, we will learn about toArray() method of SortedMap class. It is used to convert the given SortedMap to an array. We will learn about toArray() method with examples.
Submitted by Shivang Yadav, on December 20, 2020

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.

SortedMap toArray() Method

SortedMap toArray() method in Scala is used to convert the given sortedMap to an array. It stores the elements in a 2-D array in which each row consists of the key and value of the map.

Syntax:

resArray = sortedMap.toArray

Parameter: It accepts no parameter.

Return: It returns an array that consists of elements of SortedMap.

Example 1: Program to illustrate the working of toArray() method on sortedMap.

// Program to illustrate the working of toArray() method in Scala

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 SmArray = mySortedMap.toArray
        
        print("Converted Array: ")
        for( i <- SmArray)
            print(i + "  ")
    }
}

Output:

Sorted Map: TreeMap(JavaScript -> 6, Ruby -> 8, scala -> 5)
Converted Array: (JavaScript,6)  (Ruby,8)  (scala,5)

Example 2: Program to illustrate the working of toArray() method on SortedMap

// Program to illustrate the working of toArray() method in Scala

import scala.collection.SortedMap

object myObject {
    def main(args: Array[String]) {
        val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
        val emptySortedMap = mySortedMap.empty
    
        println("Sorted Map: " + emptySortedMap)
        
        val SmArray = emptySortedMap.toArray
    
        print("Converted Array: ")
        for( i <- SmArray)
            print(i + "  ")
    }
}

Output:

Sorted Map: TreeMap()
Converted Array: 


Comments and Discussions!

Load comments ↻





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