Scala Programming: Remove single and multiple elements from a given listbuffer/list
Write a Scala program to remove single and multiple elements from 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 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)
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to add single element and multiple elements to a given listbuffer/list.
Next: Write a Scala program to delete element(s) from a given List.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics