Q:

Write a Scala program to remove single and multiple elements from a given listbuffer/list

0

Write a Scala program to remove single and multiple elements from a given listbuffer/list.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now