Home
### Set

A set represents an unordered collection of distinct elements.

Scala provides both immutable and mutable sets. By default, Set is equal to scala.collection.immutable.Set.

You can create sets using the Set constructor, or by converting any other collection to a Set using its toSet method:

scala> var s = Set(2, 3, 4, 5, 7) s: scala.collection.immutable.Set[Int] = Set(5, 2, 7, 3, 4) scala> var s1 = Set[Int]() s1: scala.collection.immutable.Set[Int] = Set() scala> val a = Array(7, 4, 5, 3, 4, 2, 7, 4) a: Array[Int] = Array(7, 4, 5, 3, 4, 2, 7, 4) scala> var s2 = a.toSet s2: scala.collection.immutable.Set[Int] = Set(5, 2, 7, 3, 4) scala> s == s2 res0: Boolean = true

Important Set methods are:

- S + e returns a new set that is the union of S with element e;
- S - e returns a new set with element e removed (the new set is equal to S if S did not contain e);
- S union T returns a new set that is the union of S and T;
- S intersect T returns a new set that is the intersection of S and T;
- S diff T returns a new set that is the difference of S and T. It contains all elements of S that are not in T;
- S contains x returns true if x is an element of S;
- S subsetOf T returns true if S is a subset of T;

scala.collection.mutable.Set provides mutable sets. In addition to the methods above, mutable sets provide += and -= operators:

- S += e adds element e to the set S;
- S -= e removes element e from the set S.