than mutable sets. So if you expect the size of a set to be small, try to make it immutable.
Two Set subtraits are SortedSet and BitSet. These are explained in the following subsections.
Sorted sets
A SortedSet is a set where, no matter what order elements were added to the set, the elements are traversed in sorted order. The default representation of a SortedSet is an ordered binary tree maintaining the invariant that all elements in the left subtree of a node are smaller than all elements in the right subtree. That way, a simple in-order traversal can return all tree elements in increasing order. Scala’s class immutable.TreeSet uses a red-black tree implementation to maintain this ordering invariant, and at the same time keep the tree balanced—meaning that all paths from the root of the tree to a leaf have about the same length.
To create an empty tree set, you could first specify the desired ordering. For example, here is an ordering that puts strings in reverse order:
scala> val myOrdering = Ordering.fromLessThan[String](_ > _)
myOrdering: scala.math.Ordering[String] = ...
Then, to create an empty tree set with that ordering, use:
scala> import scala.collection.immutable.TreeSet import scala.collection.immutable.TreeSet
scala> TreeSet.empty(myOrdering)
res12: scala.collection.immutable.TreeSet[String] = TreeSet()
Or you can leave out the ordering argument but give an element type or the empty set. In that case, the default ordering on the element type will be used:
scala> val set = TreeSet.empty[String]
set: scala.collection.immutable.TreeSet[String] = TreeSet()
If you create new sets from a tree set (for instance by concatenation or filtering), they will keep the same ordering as the original set. For example:
scala> val numbers = set + ("one", "two", "three", "four") numbers: scala.collection.immutable.TreeSet[String] =
TreeSet(four, one, three, two)