Getting the union, intersection, and difference of Scala sets

A cool thing about Scala sets — and some other Scala collections — is that you can easily determine the union, intersection, and difference between two sets. The following examples demonstrate how the methods work.

Sample data

First, we create two sets that have a slight overlap:

scala> val low = 1 to 5 toSet
low: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

scala> val medium = (3 to 7).toSet
medium: scala.collection.immutable.Set[Int] = Set(5, 6, 7, 3, 4)

Union

Now we exercise the methods. First, the union:

scala> val uniq = low.union(medium)
uniq: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 4)

Intersection

Next we check the intersection with the intersect method:

scala> val i = low.intersect(medium)
i: scala.collection.immutable.Set[Int] = Set(5, 3, 4)

Differences

Those methods should give you the same results regardless of which object invokes the methods. However, the results from the difference method (diff, actually) will vary depending on which object you call the diff method:

scala> val diff = low.diff(medium)
diff: scala.collection.immutable.Set[Int] = Set(1, 2)

scala> val diff = medium.diff(low)
diff: scala.collection.immutable.Set[Int] = Set(6, 7)

Summary

That's today’s quick examples of the Scala Set class union, intersect, and diff methods. I hope it was helpful.

For more information on the Scala Set classes, see the Scaladoc: