If I have a List of Ints like:
val myList = List(3,2,1,9)
what is the right/preferred way to create a SortedSet from a List or Seq of Ints, where the items are sorted from least to greatest?
If you held a gun to my head I would have said:
val itsSorted = collection.SortedSet(myList)
but I get an error regarding that there is no implicit ordering defined for List[Int].
Use:
collection.SortedSet(myList: _*)
The way you used it, the compiler thinks you want to create a SortedSet[List[Int]] not a SortedSet[Int]. That's why it complains about no implicit Ordering for List[Int].
Notice the repeated parameter of type A* in the signature of the method:
def apply [A] (elems: A*)(implicit ord: Ordering[A]): SortedSet[A]
To treat myList as a sequence argument of A use, the _* type annotation.
You could also take advantage of the CanBuildFrom instance, and do this:
val myList = List(3,2,1,9)
myList.to[SortedSet]
// scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2, 3, 9)
There doesn't seem to be a constructor that directly accepts List (correct me if I'm wrong). But you can easily write
val myList = List(3,2,1,9)
val itsSorted = collection.SortedSet.empty[Int] ++ myList
to the same effect. (See http://www.scala-lang.org/docu/files/collections-api/collections_20.html.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With