How to convert a Set to a SortedSet in Scala

Without much explanation today, here are different ways to create a sorted set from a Set in Scala:

val set = Set(1, 6, 2, 12, 7, 3, 11)
val ss = collection.immutable.SortedSet[Int]() ++ set
val ss = collection.immutable.TreeSet[Int]() ++ set
val ss = collection.mutable.SortedSet(set.toList: _*)

Here’s what this looks like in the REPL:

scala> val set = Set(1, 6, 2, 12, 7, 3, 11)
set: scala.collection.immutable.Set[Int] = Set(1, 6, 2, 12, 7, 3, 11)

scala> val ss = collection.immutable.SortedSet[Int]() ++ set
ss: scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2, 3, 6, 7, 11, 12)

scala> val ss = collection.immutable.TreeSet[Int]() ++ set
ss: scala.collection.immutable.TreeSet[Int] = TreeSet(1, 2, 3, 6, 7, 11, 12)

scala> val ss = collection.mutable.SortedSet(set.toList: _*)
ss: scala.collection.mutable.SortedSet[Int] = TreeSet(1, 2, 3, 6, 7, 11, 12)

I haven’t done any performance comparisons on these approaches, I just thought I’d share them here today.

Note that if you want to convert a Scala Set to a sorted sequence, you can also use this approach:

val sortedSeq = set.toSeq.sorted