×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala SortedMap copyToArray() Method

By IncludeHelp Last updated : November 14, 2024

Map is a collection that stores its elements as key-value pairs, like a dictionary. Also, known as hash tables, maps have unique keys that are used to retrieve the value related to the key.

SortedMap copyToArray() Method

The copyToArray() method on SortedMap in scala is used to copy the contents of the SortedMap to an array. The created will be an array of arrays where the easy inner array consists of a key-value pair from the maps.

Syntax

sortedMapName.copyToArray(arrayName)

Parameters

The method takes only one parameter which is the array in which the elements are to be copied.

Return Type

None

Example 1

import scala.collection.immutable.SortedMap

object myObject {
    def main(args: Array[String]): Unit = {
        var myMap = SortedMap(1 -> "Scala", 3 -> "Java", 9 -> "JavaScript")
        println("The contents of sorted Map are " + myMap);
    
        val myArray : Array[Any] = Array(0, 0, 0)
        
        myMap.copyToArray(myArray)
    
        println("The content of the array are ")
        for(values <- myArray)
            println(values)
    }       
}

Output

The contents of sorted Map are TreeMap(1 -> Scala, 3 -> Java, 9 -> JavaScript)
The content of the array are 
(1,Scala)
(3,Java)
(9,JavaScript)

Example 2

import scala.collection.immutable.SortedMap

object myObject {
    def main(args: Array[String]): Unit = {
        var myMap = SortedMap(1 -> "Scala", 3 -> "Java", 9 -> "JavaScript", 4 -> "C++", 3 -> "Java")
        
        println("The contents of sorted Map are " + myMap);
        
        val myArray : Array[Any] = Array(0, 0, 0, 0, 0)
        
        myMap.copyToArray(myArray)
        
        println("The content of the array are ")
        for(values <- myArray)
            println(values)
    }       
}

Output

The contents of sorted Map are TreeMap(1 -> Scala, 3 -> Java, 4 -> C++, 9 -> JavaScript)
The content of the array are 
(1,Scala)
(3,Java)
(4,C++)
(9,JavaScript)
0

Comments and Discussions!

Load comments ↻





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