w3resource

Difference between two given lists

Scala Programming List Exercise-9 with Solution

Write a Scala program to get the difference between two given lists.

Sample Solution:

Scala Code:

object Scala_List
{
def main(args: Array[String]): Unit = 
 {
   val list1 = List("Red","Blue","Blue","Green","Black")
   val list2 = List("Blue","White")
   println("Original lists")
   println(list1)
   println(list2)
   println("Difference of the said two lists(list1-list2):")
   val temp = list2.toSet
   val result = list1.filterNot(temp)
   println(result)   
   println("Difference of the said two lists(list2-list1):")
   val temp1 = list1.toSet
   val result1 = list2.filterNot(temp1)
   println(result1)   
  }
}

Sample Output:

Original lists
List(Red, Blue, Blue, Green, Black)
List(Blue, White)
Difference of the said two lists(list1-list2):
List(Red, Green, Black)
Difference of the said two lists(list2-list1):
List(White)

Scala Code Editor :

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

Previous: Write a Scala program to check a given list is empty or not.
Next: Write a Scala program to find the first and last element of given list.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/list/scala-list-exercise-9.php