Scala for-comprehension 返回有序映射 [英] Scala for-comprehension returning an ordered map
本文介绍了Scala for-comprehension 返回有序映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 for-comprehension 返回我可以分配给有序 Map 的内容?这是我拥有的代码的简化:
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)
我需要确保我的结果是一个有序的 Map,按照从 for-comprehension 返回的顺序元组.
I need to make sure my result is an ordered Map, in the order tuples are returned from the for-comprehension.
上面的,我得到错误:
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 调用.
but then I assume the map won't be ordered, and I need an explicit toMap call.
我怎样才能做到这一点?
How can I achieve this?
推荐答案
可以通过使用 ListMap 类的伴生对象来实现,如下所示:
You can achieve do it by using the companion object of ListMap class as followings:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result = ListMap((for(foo <- myList) yield (foo.name, foo.bar)):_*)
这篇关于Scala for-comprehension 返回有序映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文