Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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?