简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM