- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Whats the nicest way to convert a Set into a SortedSet by providing an Ordering?
Fri, 2010-07-16, 01:17
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
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