Home »
Scala
Scala SortedMap copyToArray() Method with Example
Here, we will learn about the copyToArray() method of SortedMap in Scala. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on February 07, 2021
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.
Example 1:
import scala.collection.immutable.SortedMap
object myObject {
def main(args: Array[String]) {
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]) {
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