1. Overview
In this tutorial, we’ll see how to get the difference between two lists in Scala.
2. Finding the Difference Between Two Lists
On some occasions, when we have two Lists, we may want to find which elements exist in the first but not in the second. This is called the difference between two Lists.
When finding the difference between two Lists in Scala, there are two main cases – when the Lists contain no duplicated elements and when duplicate elements exist.
2.1. Finding the Difference Between Two Lists With No Duplicates
When we have two different lists, we can get the difference between them by using the List.diff() standard method:
scala> val l1WithNoDupes = List(1,2,3)
l1: List[Int] = List(1, 2, 3)
scala> val l2 = List(3,4,5)
l2: List[Int] = List(3, 4, 5)
scala> l1WithNoDupes.diff(l2)
res0: List[Int] = List(1, 2)
List.diff() method returns elements from the first list that are not in the second.
2.2. Finding the Difference Between Two Lists With Duplicates
When the lists contain duplicated elements, not all elements would be considered to exist in the second list by just using the List.diff() method:
scala> val l1WithDupes = List(1,2,3,3)
l1: List[Int] = List(1, 2, 3, 3)
scala> val l2 = List(3,4,5)
l2: List[Int] = List(3, 4, 5)
scala> l1WithDupes.diff(l2)
res1: List[Int] = List(1, 2, 3)
We should use the List.filterNot() method to get the unique difference of elements from a List that exist in a second List:
scala> val l1 = List(1,2,3,3)
l1: List[Int] = List(1, 2, 3, 3)
scala> val l2 = List(3,4,5)
l2: List[Int] = List(3, 4, 5)
scala> l1.filterNot(el => l2.contains(el))
res12: List[Int] = List(1, 2)
scala> l1.filterNot(l2.contains)
res13: List[Int] = List(1, 2)
scala> l1.filterNot(l2.toSet)
res14: List[Int] = List(1, 2)
It’s worth noting that in the above example, we see a few alternative syntaxes. First, we pass the more explicit predicate to check if an element exists in the l2 list. We then move to the shorter syntax. Finally, in the last example, we use the fact that a Set may also be seen as a function to have an even more concise syntax.
3. Conclusion
In this article, we have learned how to find the difference between two Lists, including when a List contains repeated elements.