Home »
Scala
How to add elements to a List in Scala?
By IncludeHelp Last updated : October 20, 2024
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.
To add elements to a list there are two methods,
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 +:
Example
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)
Using ListBuffer
ListBuffer is a mutable list that has characteristics of a List but elements can be added or removed from the list.
Example
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:
val listName = listBufferName.toList
Creating empty ListBiffer in Scala
You can also create an empty ListBuffer, just by mentioning its datatype.
Syntax:
var listBufferName = new ListBuffer[dataType]()
Example
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)