scala中创建时间序列
Scala | 建立地图 (Scala | Creating a map)
A map is a special type of collection that stores data in key-value pairs. These are also known as hashtables. The keys that are used to extract the value should be unique.
映射是一种特殊的集合类型,它以键值对的形式存储数据。 这些也称为哈希表。 用于提取值的键应该是唯一的。
You can create a mutable as well as an immutable map in Scala. The immutable version is inbuilt but mutable map creation needs explicit import.
您可以在Scala中创建可变的和不变的地图 。 不可变版本是内置的,但可变的地图创建需要显式导入。
Syntax:
句法:
val mapName = Map("key1"->"value1", ...)
Now let's see how to create a mutable map in Scala?
现在让我们看看如何在Scala中创建可变地图?
object myObject {
def main(args: Array[String]) {
val cars = Map("Honda" -> "Amaze", "Suzuki" -> "Baleno", "Audi" -> "R8", "BMW" -> "Z4")
println(cars)
}
}
Output
输出量
Map(Honda -> Amaze, Suzuki -> Baleno, Audi -> R8, BMW -> Z4)
Generally, the above way of creating a map is used. But sometimes to make the code more clear, another way of declaring maps is used.
通常,使用以上创建地图的方式。 但是有时为了使代码更清晰,使用了另一种声明地图的方法。
val cars = Map(
("Honda" -> "Amaze"),
("Suzuki" -> "Baleno"),
("Audi" -> "R8"),
("BMW" -> "Z4")
)
This method can also be used as the maps are created as a key->value pair, so pair are enclosed together in the brackets. Both styles are valid and use can use any.
由于将映射创建为键->值对,因此也可以使用此方法,因此,将这些对括在括号中。 两种样式均有效,并且可以使用任何样式。
Scala可变地图 (Scala mutable maps)
Mutable maps are required when we need to add more elements to the map after declaring it.
当我们需要在声明之后向地图添加更多元素时,需要可变地图。
For creating a mutable map use scala.collection.mutable.Map or import the same for creating an immutable map.
要创建可变映射,请使用scala.collection.mutable.Map或将其导入以创建不可变映射。
Syntax:
句法:
var map_name = collection.mutable.Map(
"key1"->"value1",
"key2"->"value2", ...
)
Program to create a mutable map in Scala
在Scala中创建可变地图的程序
object myObject {
def main(args: Array[String]) {
val cars = collection.mutable.Map(
"Honda" -> "Amaze",
"Suzuki" -> "Baleno",
"Audi" -> "R8"
)
println(cars)
println("Adding new elements to the map")
cars += ("BMW" -> "Z4")
println(cars)
}
}
Output:
输出:
HashMap(Audi -> R8, Honda -> Amaze, Suzuki -> Baleno)
Adding new elements to the map
HashMap(BMW -> Z4, Audi -> R8, Honda -> Amaze, Suzuki -> Baleno)
You can create an empty mutable map initially and then add elements to it, using +=.
您可以先创建一个空的可变映射,然后使用+ =向其添加元素。
object myObject {
def main(args: Array[String]) {
val cars = collection.mutable.Map[String, String]()
println(cars)
println("Adding new elements to the map")
cars += ("BMW" -> "Z4")
println(cars)
}
}
Output:
输出:
HashMap()
Adding new elements to the map
HashMap(BMW -> Z4)
翻译自: https://www.includehelp.com/scala/how-to-create-a-map-in-scala.aspx
scala中创建时间序列