ADVERTISEMENT
ADVERTISEMENT

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: 
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.