Andy
Andy

Reputation: 1560

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

Upvotes: 25

Views: 13284

Answers (4)

Ben Challenor
Ben Challenor

Reputation: 3395

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)

Upvotes: 13

Landei
Landei

Reputation: 54584

This is especially useful if you have to map anyway:

import scala.collection.breakOut

val s: collection.SortedSet[Int] = List(1,2,3,4).map(identity)(breakOut)
//--> s: scala.collection.SortedSet[Int] = TreeSet(1, 2, 3, 4)

Upvotes: 4

huynhjl
huynhjl

Reputation: 41646

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.

Upvotes: 39

Mechanical snail
Mechanical snail

Reputation: 30647

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

Upvotes: 8

Related Questions