Create SortedMap from Iterator in scala
Asked Answered
E

1

6

I have an val it:Iterator[(A,B)] and I want to create a SortedMap[A,B] with the elements I get out of the Iterator. The way I do it now is:

val map = SortedMap[A,B]() ++ it

It works fine but feels a little bit awkward to use. I checked the SortedMap doc but couldn't find anything more elegant. Is there something like:

 it.toSortedMap 

or

SortedMap.from(it)

in the standard Scala library that maybe I've missed?

Edit: mixing both ideas from @Rex's answer I came up with this:

SortedMap(it.to:_*)

Which works just fine and avoids having to specify the type signature of SortedMap. Still looks funny though, so further answers are welcome.

Eucalyptus answered 23/2, 2013 at 15:53 Comment(0)
C
6

The feature you are looking for does exist for other combinations, but not the one you want. If your collection requires just a single parameter, you can use .to[NewColl]. So, for example,

import collection.immutable._

Iterator(1,2,3).to[SortedSet]

Also, the SortedMap companion object has a varargs apply that can be used to create sorted maps like so:

SortedMap( List((1,"salmon"), (2,"herring")): _* )

(note the : _* which means use the contents as the arguments). Unfortunately this requires a Seq, not an Iterator.

So your best bet is the way you're doing it already.

Constabulary answered 23/2, 2013 at 16:4 Comment(3)
Very good points both, mixing them I came up with an idea, which i added to the question.Eucalyptus
@Eucalyptus - Good idea! Note that it's not as efficient as the ++ solution because it does need to create an intermediate Seq. But if you aren't in a situation where efficiency matters much (which is most situations) then it could be a good alternative!Constabulary
Note SortedMap.from is part of the API of Scala 2.13.Dialogize

© 2022 - 2024 — McMap. All rights reserved.