Scala 理解返回有序映射
如何使用 for 理解来返回可以分配给有序 Map 的内容?这是我的代码的简化:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: ListMap[String, Bar] =
for {
foo <- myList
} yield (foo.name, foo.bar)
我需要确保我的结果是一个有序的 Map,按照从 for-compression 返回元组的顺序。
通过上面的内容,我收到错误:
error: type mismatch;
found : scala.collection.mutable.Buffer[(String,Bar)]
required: scala.collection.immutable.ListMap[String,Bar]
foo <- myList
这可以编译:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: Predef.Map[String, Bar] =
{
for {
foo <- myList
} yield (foo.name, foo.bar)
} toMap
但随后我假设地图不会被排序,并且我需要显式的 toMap 调用。
我怎样才能实现这个目标?
How can I use a for-comprehension that returns something I can assign to an ordered Map? This is a simplification of the code I have:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: ListMap[String, Bar] =
for {
foo <- myList
} yield (foo.name, foo.bar)
I need to make sure my result is an ordered Map, in the order tuples are returned from the for-comprehension.
With the above, I get the error:
error: type mismatch;
found : scala.collection.mutable.Buffer[(String,Bar)]
required: scala.collection.immutable.ListMap[String,Bar]
foo <- myList
This compiles:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: Predef.Map[String, Bar] =
{
for {
foo <- myList
} yield (foo.name, foo.bar)
} toMap
but then I assume the map won't be ordered, and I need an explicit toMap call.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,collection.breakOut是你的好朋友,
如果使用for-commplion表达式很重要,那么将按如下方式完成,
Scala 2.8 breakOut 已经很好地解释了 collection.breakOut 。
The collection.breakOut is your good friend in such a case,
If it is important to use for-comprehension expression, it will be done as follows,
Scala 2.8 breakOut has explained collection.breakOut very well.
您可以使用 ListMap 类的伴生对象来实现,如下所示:
You can achieve do it by using the companion object of ListMap class as followings: