Create SortedMap from Iterator in scala

偶尔善良 提交于 2019-12-10 14:49:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15042421/create-sortedmap-from-iterator-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!