Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List of Ints to a SortedSet in Scala

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].

like image 423
Andy Avatar asked Jul 13 '11 04:07

Andy


3 Answers

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.

like image 134
huynhjl Avatar answered Oct 09 '22 23:10

huynhjl


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)
like image 35
Ben Challenor Avatar answered Oct 09 '22 21:10

Ben Challenor


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.)

like image 33
Mechanical snail Avatar answered Oct 09 '22 21:10

Mechanical snail