Scala Programming: Add single element and multiple elements to a given listbuffer/list
Scala Programming List Exercise-2 with Solution
Write a Scala program to add single element and multiple elements to a given listbuffer/list.
Sample Solution:
Scala Code:
object Scala_List
{
import scala.collection.mutable.ListBuffer
def main(args: Array[String]): Unit =
{
//As a List is immutable we use ListBuffer
var colors = new ListBuffer[String]()
println("Add Single element in the said list:")
colors +="Red"
colors +="Green"
colors +="Black"
println(colors)
println("Add multiple elements in the said list:")
colors ++= List("Orange", "Pink", "Black")
println(colors)
println("Convert the ListBuffer to a List:")
val colors_list = colors.toList
println(colors_list)
}
}
Sample Output:
Add Single element in the said list: ListBuffer(Red, Green, Black) Add multiple elements in the said list: ListBuffer(Red, Green, Black, Orange, Pink, Black) Convert the ListBuffer to a List: List(Red, Green, Black, Orange, Pink, Black)
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to create a list in different ways.
Next: Write a Scala program to remove single and multiple elements from a given listbuffer/list.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework