This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Whats the nicest way to convert a Set into a SortedSet by providing an Ordering?

1 reply
Ben Hutchison 3
Joined: 2009-11-02,
User offline. Last seen 42 years 45 weeks ago.

I was slightly surprised to find that turning a Set into a SortedSet
required me to first create an empty SortedSet, then add the Set's
contents to it

Two other options that came to mind are shown below. One was to use
what Groovy calls the "spread operator" (does it have another name?)
:_*, to indicate to SortedSet.apply() that I want the contents of the
allMatches set to be added to the SortedSet.

But it seems use of the spread operator is restricted to Seq. Why not Iterable?

Also, I kinda hoped for some kind of sortedBy method that would turn a
Set into a SortedSet in a single call. Impractical?

Have I missed a nicer way to do it?

val allMatches: Set[Match] = Set()
val matchesSortedByDate =
scala.collection.SortedSet.empty[Match](Ordering.by(_.date)) ++
allMatches

//type mismatch; found : scala.collection.immutable.Set[Match]
required: Seq[?]
//val matchesSortedByDate =
scala.collection.SortedSet(allMatches:_*)(Ordering.by(_.date))

//No such method
//val matchesSortedByDate = allMatches.sortedBy(Ordering.by(_.date))

-Ben

Sylvain HENRY
Joined: 2009-05-28,
User offline. Last seen 42 years 45 weeks ago.
Re: Whats the nicest way to convert a Set into a SortedSet by p

Le 16/07/2010 02:17, Ben Hutchison a écrit :
> I was slightly surprised to find that turning a Set into a SortedSet
> required me to first create an empty SortedSet, then add the Set's
> contents to it
>
> Two other options that came to mind are shown below. One was to use
> what Groovy calls the "spread operator" (does it have another name?)
> :_*, to indicate to SortedSet.apply() that I want the contents of the
> allMatches set to be added to the SortedSet.
>
> But it seems use of the spread operator is restricted to Seq. Why not Iterable?
>
> Also, I kinda hoped for some kind of sortedBy method that would turn a
> Set into a SortedSet in a single call. Impractical?
>
> Have I missed a nicer way to do it?
>
> val allMatches: Set[Match] = Set()
> val matchesSortedByDate =
> scala.collection.SortedSet.empty[Match](Ordering.by(_.date)) ++
> allMatches
>
> //type mismatch; found : scala.collection.immutable.Set[Match]
> required: Seq[?]
> //val matchesSortedByDate =
> scala.collection.SortedSet(allMatches:_*)(Ordering.by(_.date))
Maybe:
val matchesSortedByDate = SortedSet(allMatches.iterator.toList
:_*)(Ordering.by(_.date))
> //No such method
> //val matchesSortedByDate = allMatches.sortedBy(Ordering.by(_.date))
>
>
> -Ben

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland