object Scala_List
{
import scala.collection.mutable.ListBuffer
def main(args: Array[String]): Unit =
{
//As a List is immutable we use ListBuffer and finally convert the ListBuffer to list.
var colors = new ListBuffer[String]()
colors += "Red"
colors += "Green"
colors += "Black"
colors += "Orange"
colors += "Pink"
println("Original ListBuffer:")
println(colors)
println("Remove one element:")
colors -= "Red"
println(colors)
println("Remove multiple elements:")
println(colors)
colors --= Seq("Black", "Pink")
println("After removing two elements, final ListBuffer:")
println(colors)
println("Convert the ListBuffer to a List:")
val colors_list = colors.toList
println(colors_list)
}
}
Sample Output:
riginal ListBuffer:
ListBuffer(Red, Green, Black, Orange, Pink)
Remove one element:
ListBuffer(Green, Black, Orange, Pink)
Remove multiple elements:
ListBuffer(Green, Black, Orange, Pink)
After removing two elements, final ListBuffer:
ListBuffer(Green, Orange)
Convert the ListBuffer to a List:
List(Green, Orange)
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer