scala集合中添加元素
In Scala, lists are immutable data structures in which adding new elements is not allowed. So, here we will solve this problem that is generally done in functional programming paradigms.
在Scala中,列表是不可变的数据结构,其中不允许添加新元素。 因此,在这里我们将解决通常在函数式编程范例中完成的问题。
To add elements to a list there are two methods,
要将元素添加到列表中 ,有两种方法:
1)将元素添加到Scala列表 (1) Appending elements to Scala list)
As the list is immutable when adding a new element to it, we will append an element to a new list.
由于添加新元素时列表是不可变的,因此我们将元素添加到新列表中 。
Done using the following operators,
使用以下运算符完成,
Prepending operator (::)
前置运算符( : :)
Appending operator +:
追加运算符+:
Program:
程序:
object MyClass {
def main(args: Array[String]) {
var progLang = List("Java", "Scala")
println("Programming languages: " + progLang)
println("Prepending elements to list")
progLang = "C++" :: progLang
println("Programming languages: " + progLang)
println("Appending elements to list")
progLang = progLang :+ "Python"
println("Programming languages: " + progLang)
}
}
Output
输出量
Programming languages: List(Java, Scala)
Prepending elements to list
Programming languages: List(C++, Java, Scala)
Appending elements to list
Programming languages: List(C++, Java, Scala, Python)
2)使用ListBuffer (2) Using ListBuffer)
ListBuffer is a mutable list that has characteristics of a List but elements can be added or removed from the list.
ListBuffer是具有列表特性的可变列表,但是可以从列表中添加或删除元素。
Program:
程序:
import scala.collection.mutable.ListBuffer
object MyClass {
def main(args: Array[String]) {
var progLang = ListBuffer("Java", "Scala")
println("Programming Languages :" + progLang)
println("Adding New elments to ListBuffer")
progLang += "C++"
println("Programming Languages :" + progLang)
}
}
Output
输出量
Programming Languages :ListBuffer(Java, Scala)
Adding New elments to ListBuffer
Programming Languages :ListBuffer(Java, Scala, C++)
You can convert this ListBuffer to a List if you need to use some characteristics of list:
如果需要使用list的某些特征,可以将此ListBuffer转换为List:
val listName = listBufferName.toList
在Scala中创建空的ListBiffer (Creating empty ListBiffer in Scala)
You can also create an empty ListBuffer, just by mentioning its datatype.
您还可以仅通过提及其数据类型来创建一个空的ListBuffer。
Syntax:
句法:
var listBufferName = new ListBuffer[dataType]()
Program:
程序:
import scala.collection.mutable.ListBuffer
object MyClass {
def main(args: Array[String]) {
var progLang = ListBuffer[String]()
println("Programming Languages :" + progLang)
println("Adding New elments to ListBuffer")
progLang += "C++"
progLang += "Java"
progLang += "Scala"
println("Programming Languages :" + progLang)
}
}
Output
输出量
Programming Languages :ListBuffer()
Adding New elments to ListBuffer
Programming Languages :ListBuffer(C++, Java, Scala)
翻译自: https://www.includehelp.com/scala/how-to-add-elements-to-a-list-in-scala.aspx
scala集合中添加元素