在Scala中从Iterator创建SortedMap [英] Create SortedMap from Iterator in scala
问题描述
val it:Iterator [(A,B)]
并且我想创建一个 SortedMap [A,B] code>与从 Iterator
中获取的元素。我现在这样做是: val map = SortedMap [A,B]()++ it
它工作正常,但感觉有点尴尬使用。我检查了 SortedMap
doc,但找不到更优雅的东西。是否有类似:
it.toSortedMap
或
SortedMap.from(it)
在标准Scala库中,也许我错过了?
编辑:混合两个想法从@ Rex的答案我想出了这样:
SortedMap _ *)
这种方法很好,避免了指定 SortedMap
。
解决方案您正在寻找的功能对其他组合存在,但不是你想要的。如果你的集合只需要一个参数,你可以使用 .to [NewColl]
。因此,例如,
import collection.immutable._
迭代器).to [SortedSet]
此外, SortedMap
companion对象有一个varargs apply,可用于创建如下所示的排序映射:
SortedMap salmon),(2,herring)):_ *)
code>:_ *
这意味着使用内容作为参数)。不幸的是,这需要一个 Seq
,而不是迭代器
。 所以你最好的赌注是你已经做的方式。
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.
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.
这篇关于在Scala中从Iterator创建SortedMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!