w3resource

Scala Programming: Delete element(s) from a given List

Scala Programming List Exercise-4 with Solution

Write a Scala program to delete element(s) from a given List.

Sample Solution:

Scala Code:

object Scala_List
{
  def main(args: Array[String]): Unit = 
 {
   val nums = List(1, 3, 5, 7, 9, 11, 14, 12)
   println("Original list:")
   println(nums)   
  //As scala List is immutable, so we can’t delete elements from it, but
  //filter out element(s) as per requirement.
   println("Filter out 3 from the above list:")
   val nums1 = nums.filter(_ != 3) 
   println(nums1)
   println("Filter out numbers which are greater than 10:")
   val nums2 = nums.filter(_ > 10) 
   println(nums2)   
  }
}

Sample Output:

Original list:
List(1, 3, 5, 7, 9, 11, 14, 12)
Filter out 3 from the above list:
List(1, 5, 7, 9, 11, 14, 12)
Filter out numbers which are greater than 10:
List(11, 14, 12)

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to remove single and multiple elements from a given listbuffer/list.
Next: Write a Scala program to iterate over a list to print the elements and calculate the sum and product of all elements of this list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.