×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

SortedMap toArray() in Scala Method

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.

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

Parameters

It accepts no parameter.

Return Type

It returns an array that consists of elements of SortedMap.

Example 1

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

import scala.collection.immutable.SortedMap

object MyObject {
    def main(args: Array[String]): Unit = {
        val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
        println("Sorted Map: " + mySortedMap)
        
        val smArray = mySortedMap.toArray
        
        print("Converted Array: ")
        for ((key, value) <- smArray) {
            print(s"($key, $value)  ")
        }
    }
}

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

import scala.collection.immutable.SortedMap

object MyObject {
    def main(args: Array[String]): Unit = {
        val mySortedMap = SortedMap("scala" -> 5, "JavaScript" -> 6, "Ruby" -> 8)
        val emptySortedMap = mySortedMap.empty
        
        // Non-empty SortedMap
        println("Non-empty Sorted Map: " + mySortedMap)
        
        val smArray = mySortedMap.toArray
        print("Converted Array from non-empty map: ")
        for ((key, value) <- smArray) {
            print(s"($key, $value)  ")
        }

        // Empty SortedMap
        println("\n\nEmpty Sorted Map: " + emptySortedMap)
        
        val emptyArray = emptySortedMap.toArray
        print("Converted Array from empty map: ")
        for ((key, value) <- emptyArray) {
            print(s"($key, $value)  ")
        }
    }
}

Output

Sorted Map: TreeMap()
Converted Array: 

Comments and Discussions!

Load comments ↻





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